package com.bill.common.user.service;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.bill.common.business.dao.IBuyDAO;
import com.bill.common.business.dao.IMatchDAO;
import com.bill.common.business.dao.ISellDAO;
import com.bill.common.business.dto.BuyDTO;
import com.bill.common.business.dto.SellDTO;
import com.bill.common.business.service.IBuyService;
import com.bill.common.business.service.ISellService;
import com.bill.common.system.dao.IActivationCodeDAO;
import com.bill.common.system.dao.IExtractDAO;
import com.bill.common.system.dao.IGenerateRegisterCodeDao;
import com.bill.common.system.dao.IOrderDAO;
import com.bill.common.system.dao.ITransactionRecordDAO;
import com.bill.common.system.dto.ExtractDTO;
import com.bill.common.system.dto.GenealogicalTreeDTO;
import com.bill.common.system.dto.RuleDTO;
import com.bill.common.system.entity.ActivationCode;
import com.bill.common.system.entity.TransactionRecord;
import com.bill.common.system.service.IActivationCodeService;
import com.bill.common.system.service.IEmailService;
import com.bill.common.system.service.IExtractService;
import com.bill.common.system.service.IGenerateRegisterCodeService;
import com.bill.common.system.service.IRuleService;
import com.bill.common.system.service.ITransactionRecordService;
import com.bill.common.system.service.RuleService;
import com.bill.common.user.dao.IRegisterUserDAO;
import com.bill.common.user.dto.AccountDTO;
import com.bill.common.user.dto.FuWuJiangDTO;
import com.bill.common.user.dto.RegUserBasicDTO;
import com.bill.common.user.dto.RegisterUserDTO;
import com.bill.common.user.dto.RegisterUserGridDTO;
import com.bill.common.user.dto.RegisterUserQueryDTO;
import com.bill.common.user.dto.XPTreeViewDTO;
import com.bill.common.user.entity.Account;
import com.bill.common.user.entity.RegisterUser;
import com.bill.common.utils.AES;
import com.bill.common.utils.TranType;
import com.sinba.common.dto.PageDTO;
import com.sinba.common.exception.ApplicationException;

public class RegisterUserService implements IRegisterUserService {

	@Autowired
	private IGenerateRegisterCodeService generateRegisterCodeService;
	@Autowired
	private IRegisterUserDAO registerUserDAO;
	@Autowired
	private IRuleService ruleService;
	@Autowired
	private ITransactionRecordDAO transactionRecordDAO;
	@Autowired
	private ITransactionRecordService transactionRecordService;
	@Autowired
	private IEmailService emailService;
	@Autowired
	private IActivationCodeDAO activationCodeDAO;
	@Autowired
	private IOrderDAO orderDAO;
	@Autowired
	private IExtractDAO extractDAO;
	@Autowired
	private IBonusService bonusService;
	@Autowired
	private IAccountService accountService;
	@Autowired
	private IExtractService extractService; 
	@Autowired
	private IBuyDAO buyDAO;
	@Autowired
	private ISellDAO sellDAO;
	@Autowired
	private IMatchDAO matchDAO;
	@Autowired
	private IGenerateRegisterCodeDao generateRegisterCodeDao;
	@Autowired
	private IActivationCodeService activationCodeService;
	@Autowired
	private IBuyService buyService;
	@Autowired
	private ISellService sellService;
	
	public Double EVERY_SINGLE_SIZE = RuleService.EVERY_SINGLE_SIZE;
	public String ADD = "ADD";
	public String CUT = "CUT";
	
	/**
	 * 分页查询会员管理
	 */
	@Transactional
	public PageDTO findRegisterUserPager(RegisterUserQueryDTO qdto,String sord, String sidx){
		PageDTO p =registerUserDAO.findPager(qdto, sord, sidx);
		
		List<RegisterUser> registerUsers = (List<RegisterUser>) p.getData();
		List<RegisterUserGridDTO> userDTOList = new ArrayList<RegisterUserGridDTO>(registerUsers.size());
		for(RegisterUser regiserUser:registerUsers){
			//System.out.println(regiserUser.getRegisterLevel());
			RegisterUserGridDTO dto = new RegisterUserGridDTO();
			dto.entity2dto(regiserUser, dto);
			dto.setAsUserName(dto.getUserName());
			if(StringUtils.hasText(dto.getUserName())){
				dto.setUserName(dto.getUserName().substring(0, 1)+"**");
			}
			dto.setDeclarationCenter(regiserUser.isDeclarationCenter());
			
			//查子帐户返回总奖金
			if(StringUtils.hasText(qdto.getParentAccount())){
				boolean grantResult = transactionRecordDAO.todayIsRecord(dto.getLoginName(),TranType.RiFenHong);
				if(grantResult){
					dto.setDayFenHong(3D);
				}else{
					dto.setDayFenHong(0D);
				}
				Double balance = transactionRecordService.findUserBalance(dto.getLoginName(), "Dynamic");
				dto.setAllFenHong(balance);
			}
			
			Account ac = regiserUser.getAccount();
			if(ac!=null)
				dto.setBalance(ac.getBalance());
			userDTOList.add(dto);
		}
		p.setData(userDTOList);
		
		return p;
	};
	//会员登录
	@Transactional
	public RegisterUserDTO userLogin(RegisterUserDTO dto,String level){
		RegisterUserDTO userDTO = new RegisterUserDTO();
		boolean result = false;
		RegisterUser user = registerUserDAO.findUniqueBy("loginName",dto.getLoginName());
		if(user!=null){
			if("password1".equals(level) && user.getPassword1().equals(dto.getPassword1())){
				
				result=true;
			}
			if("password2".equals(level) && user.getPassword2().equals(dto.getPassword2())){
				result=true;
			}
			if("password3".equals(level) && user.getPassword3().equals(dto.getPassword3())){
				result=true;
			}
		}
		if(result){
			userDTO.setLoginName(user.getLoginName());
			userDTO.setUserName(user.getUserName());
		}else
			userDTO = null;
		return userDTO;
		
		
	};
	
	//保存用户/用户注册
	@Transactional
	public String saveRegisterUser(RegisterUserDTO dto){
		try {
			RegisterUser reg = registerUserDAO.findUniqueBy("loginName", dto.getLoginName());
			if(reg!=null){
				return "system_error";
			}else{
				
				//手机验证码
				ActivationCode ac = activationCodeService.authVerificationCode(dto.getMobile(), dto.getAuthCode(), "Register");
				if (ac==null) {
					return "REGISTER_CODE_INVALID";
				}
				
				//更新之前的已有的接点信息
				//updatecontact(dto.getContactNo(),dto.getRegisterLocation());
				RegisterUser entity = new RegisterUser();
				dto.dto2entity(dto, entity);
				entity.setRegisterMoney(RuleDTO.level.get(dto.getRegisterLevel()));
				boolean isSubAccount = "subAccount".equals(dto.getSubAccount());
				if (isSubAccount) {//子账户
					entity.setContactNo(null);//不需要接点人
					entity.setRegisterLocation( null );
				}else{
					//接点人(现在是用推荐人做为接点人)
					dto.setContactNo(dto.getRecommendUser());
					entity.setContactNo(dto.getRecommendUser());
					RegisterUser contactUser = registerUserDAO.findUniqueBy("loginName", dto.getContactNo());
					if(contactUser!=null){
						entity.setLinkcode(contactUser.getLinkcode()+dto.getLoginName());
						//层级累计
						entity.setLevel(contactUser.getLevel()+1);
					}
						
				}
				entity.setDeclarationCenters(dto.getDeclarationCenters());
				entity.setRegisterTime(new Date());
				entity.setStatus("NotActivation");
				if(StringUtils.hasText(dto.getStatus())){
					entity.setStatus("Activation");
					entity.setActivationTime(new Date());
				}
				if("TEST".equals(dto.getAccountType())){
					RegisterUser recommendUser = registerUserDAO.findUniqueBy("loginName", dto.getRecommendUser());
					recommendUser.setRecommendQuantity(recommendUser.getRecommendQuantity()+1);
				}
				
				registerUserDAO.save(entity);
				
				//如果是子账号则直接激活
				/*if( isSubAccount ){
					String result = subUserActivate(entity.getLoginName());
					if("failure".equals(result)){
						return "Sorry, sub-account generation fails, check the sub-account balance is adequate, thank you!<br>对不起，子帐户生成失败，请检查子帐户余额是否足够，谢谢！";
					}else{
						return "Registration is successful, your child account number is : "+entity.getLoginName()+"<br>注册成功，您的子帐户编号为："+entity.getLoginName();
					}
				}*/
				
				return "SUCCESSFUL";
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApplicationException(e.getMessage());
		}
	};
	@Transactional
	public String saveRegisterUserAuth(RegisterUserDTO dto){
		//判断要注册的会员编号是否存在
		RegisterUser reg = registerUserDAO.findUniqueBy("loginName", dto.getLoginName());
		if(reg!=null)
			return "loginNameExist";//会员编号已存在!
		
		boolean isSubAccount = false;
		if(StringUtils.hasText(dto.getParentAccount())){
			isSubAccount = true;
		}

		//如果是注册子账户
		RegisterUser parent = null;
		if ( StringUtils.hasText(dto.getParentAccount()) &&
				(parent = registerUserDAO.findUniqueBy("loginName", dto.getParentAccount() ) )!= null) {
			Double subAccount = transactionRecordService.findUserBalance( dto.getParentAccount() ,"Static");
			if (subAccount < RuleDTO.level.get( dto.getRegisterLevel() )) {
				return "staticMoneyNotEnough";
			}
			return "success";
		}
		//子帐户注册不需要验证
		if(!isSubAccount){
			//**********推荐人
			//判断推荐人是否存在
			RegisterUser reg1 = registerUserDAO.findUniqueBy("loginName", dto.getRecommendUser());
			if(reg1==null){
				return "recommendUserNotExist";//推荐人编号不存在!
			}else if(!"Activation".equals(reg1.getStatus())){
				return "RecommendUserNotActivation";//推荐人未激活，不允许注册推荐会员!
			}
			
			
			/*//**********报单人
			//判断报单人是否合理
			if(StringUtils.hasText(dto.getDeclarationCenters())){
				RegisterUser reg3 = registerUserDAO.findUniqueBy("loginName", dto.getDeclarationCenters());
				if(reg3==null)
					return "declarationCenterUserNotExist";//运营中心不存在!
				else if(!reg3.isDeclarationCenter()){
					return "declarationCenterUserNotExist";//运营中心不存在!
				}
			}
			//判断接点人是否存在
			RegisterUser reg2 = registerUserDAO.findUniqueBy("loginName", dto.getContactNo());
			
			if(reg2==null)
				return "contactNoNotExist";//接点人编号不存在!
			else if(!"Activation".equals(reg2.getStatus())){
				return "contactNoNotActivation";//接点人未激活，不允许注册下一层会员!
			}
			else{
				
				//**********接点人的左区是否已激活
				if("bArea".equals(dto.getRegisterLocation())){
					//判断接点人的左区是否已激活
					boolean result = registerUserDAO.isLeftActiveUser(reg2.getLinkcode());
					if(!result){
						return "MyNotRecommedLeftArea";//先注册左区并开通才允许注册
					}
				}
				
				//判断接点人的ABC区是否已满及位置是否正确
				List<RegisterUser> abcUser = registerUserDAO.findContactUser(new String[]{ dto.getContactNo() });
				if(abcUser.size()>=2){
					return "ABCAreaFull";//ABC区已满
				}
				boolean au = registerUserDAO.findAreaRegUser(dto.getContactNo(), "aArea");
				boolean bu = registerUserDAO.findAreaRegUser(dto.getContactNo(), "bArea");
				//boolean cu = registerUserDAO.findAreaRegUser(dto.getContactNo(), "cArea");
				if("aArea".equals(dto.getRegisterLocation())){//如果注册的是A区，则判断A区是否已注册
					if(au){
						return "aAreaExist";//A区已注册
					}
				}
				if("bArea".equals(dto.getRegisterLocation())){//如果注册的是B区，则判断B区是否已注册
					if(bu){
						return "bAreaExist";//B区已注册
					}else{
						if(!au){
							return "aAreaNotExistNotAllowRegBArea";//A区未注册，B区不允许注册!
						}
					}
				}
			}*/
//			
//			if("cArea".equals(dto.getRegisterLocation())){//如果注册的是C区，则判断C区是否已注册并且当前推荐人是否是接点人
//				if(cu){
//					return "cAreaExist";//C区已注册
//				}else if(!au || !bu){
//					return "abAreaNotExistNotAllowRegCArea";//AB区未注册满，还不能注册C区!
//				}else{
//					if(!dto.getRecommendUser().equals(dto.getContactNo())){
//						return "cAreaOnlyAllowsOneselfReg";//C区只能由自己注册!
//					}
//				}
//			}
		}
		
		return "success";
	}
	
	//编辑用户
	@Transactional
	public void editRegisterUser(RegisterUserDTO dto){
		RegisterUser entity = registerUserDAO.findById(dto.getRegisterUserId());
		entity.setMobile(dto.getMobile());
		entity.setPhone(dto.getPhone());
		entity.setBankAccount(dto.getBankAccount());
		entity.setEmail(dto.getEmail());
		entity.setAddress(dto.getAddress());
		entity.setQq(dto.getQq());
		entity.setMsn(dto.getMsn());
		entity.setPersonalLocation(dto.getPersonalLocation());
		entity.setUserName(dto.getUserName());
		entity.setAccountType(dto.getAccountType());
		entity.setRecommendUser(dto.getRecommendUser());
		//只能是从级别L5才允许直接更改级别
		if("L6".equals(dto.getRegisterLevel()) && "L5".equals(entity.getRegisterLevel())){
			entity.setRegisterLevel(dto.getRegisterLevel());
		}
		registerUserDAO.merge(entity);
		
	};
	//更新用户
	@Transactional
	public void updateRegisterUser(RegisterUserDTO dto){
		RegisterUser entity = registerUserDAO.findById(dto.getRegisterUserId());
		dto.dto2entity(dto, entity);
		registerUserDAO.merge(entity);
	};
	//删除会员
	@Transactional
	public String deleteRegisterUser(Long[] ids){
		for(Long id : ids){
			RegisterUser user  = registerUserDAO.findById(id);
			if(user!=null){
				if(user.getActivationTime()!=null){
					return "当前会员已激活，不允许删除！";
				}
				List<RegisterUser> list = registerUserDAO.findBy("contactNo", user.getLoginName());
				if(list!=null && list.size()>0){
					return "当前会员接点了其他会员，不允许删除！";
				}else{
					registerUserDAO.delete(user); 
				}
			}
		}
		return "删除成功!";
	};
	//删除会员
	@Transactional
	public String deleteRegisterUser(String loginName){
		RegisterUser user  = registerUserDAO.findUniqueBy("loginName",loginName);
		if(user!=null){
			if(user.getActivationTime()!=null){
				return "当前会员已激活，不允许删除！";
			}
			List<RegisterUser> list = registerUserDAO.findBy("contactNo", loginName);
			if(list!=null && list.size()>0){
				return "当前会员接点了其他会员，不允许删除！";
			}else{
				registerUserDAO.delete(user); 
			}
		}
		return "删除成功!";
	};
	
	//根据ID或登录名查询
	@Transactional
	public RegisterUserDTO findRegisterUserByIdOrLoginName(RegisterUserQueryDTO qdto){
		RegisterUserDTO dto = new RegisterUserDTO();
		RegisterUser user = new RegisterUser();
		if(StringUtils.hasText(qdto.getLoginName())){
			user = registerUserDAO.findUniqueBy("loginName", qdto.getLoginName());
			dto.dto2entity(user, dto);
		}
		
		if(qdto.getRegisterUserId()!=null){
			user = registerUserDAO.findById(qdto.getRegisterUserId());
			dto.dto2entity(user, dto);
		}
		
		return dto;
	};
	//验证登录名是否存在
	@Transactional
	public boolean loginNameExist(RegisterUserQueryDTO qdto){
		RegisterUser user = new RegisterUser();
		if(StringUtils.hasText(qdto.getLoginName())){
			user = registerUserDAO.findUniqueBy("loginName", qdto.getLoginName());
		}
		if(user!=null)
			return true;
		else
			return false;
	};
	//修改密码
	@Transactional
	public void updatePassword(RegisterUserDTO dto,String level){
		if(dto!=null && dto.getLoginName()!=null){
			RegisterUser user = registerUserDAO.findUniqueBy("loginName", dto.getLoginName());
			//会员密码
			if("password1".equals(level)){
				user.setPassword1(dto.getPassword1());
			}
			//账户密码
			if("password2".equals(level)){
				user.setPassword2(dto.getPassword1());	
			}
			//交易密码
			if("password3".equals(level)){
				user.setPassword3(dto.getPassword1());
			}
			registerUserDAO.merge(user);
		}
		
	};
	
	
	public boolean userValidate(String loginName,String password,String pwdLevel){
		List<RegisterUser> registerUsers = registerUserDAO.userValidate(loginName, password, pwdLevel);
		if(registerUsers!=null && registerUsers.size()>0){
			RegisterUser entity = registerUsers.get(0);
			if(entity!=null && StringUtils.hasText(entity.getLoginName())){
				
				HttpSession session = ServletActionContext.getRequest().getSession();
				ServletContext sctx = session.getServletContext();
				Map<String, HttpSession> sessionMap=null;

				if(pwdLevel.equals("password1")){
					if(sctx!=null && sctx.getAttribute("sessionMap")!=null){
						sessionMap=(HashMap<String, HttpSession>)sctx.getAttribute("sessionMap");
						if(sessionMap.get(entity.getLoginName())!=null){//在别的地方登录，强迫下线
							
							HttpSession oldSession=(HttpSession)sessionMap.get(entity.getLoginName());
							if(oldSession!=null){
								try {
									oldSession.invalidate();
								} catch (Exception e){
								}
							}
							sessionMap.remove(entity.getLoginName());
						}
					}else{
						sessionMap=new HashMap<String, HttpSession>();
					}
					//用户重新放入Map
					sessionMap.put(entity.getLoginName(),session);
					sctx.setAttribute("sessionMap", sessionMap);
					session.setAttribute("loginName", entity.getLoginName());
					session.setAttribute("userName", entity.getUserName());
					session.setAttribute("registerLevel", entity.getRegisterLevel());
					session.setAttribute("registerUserId", entity.getRegisterUserId());
					session.setAttribute("status", entity.getStatus());
				}else{
					session.setAttribute(pwdLevel, "true");
				}
				return true;
			}
		}
		return false;
	};
	/**
	 * 验证旧密码是否正确
	 * @param loginName
	 * @param password
	 * @param pwdLevel
	 * @return
	 */
	public boolean checkOrdPassword(String loginName,String password,String pwdLevel){
		List<RegisterUser> registerUsers = registerUserDAO.userValidate(loginName, password, pwdLevel);
		if(registerUsers!=null && registerUsers.size()>0)
			return true;
		else
			return false;
	}
	/**
	 * 获取用户基本信息
	 * @param loginName
	 * @return
	 */
	public RegUserBasicDTO findRegUserBasicInfo(String loginName){
		RegisterUser user = registerUserDAO.findUniqueBy("loginName",loginName);
		RegUserBasicDTO rubDTO = new RegUserBasicDTO();
		rubDTO.entity2dto(user, rubDTO);
		return rubDTO;
	}
	
	/**
	 * 修改个人资料
	 * @param dto
	 */
	@Transactional
	public String changeRegUserBasicInfo(RegUserBasicDTO dto){
		RegisterUser user = registerUserDAO.findById(dto.getRegisterUserId());
		/*RegisterUserDTO registerUserDTO = new RegisterUserDTO(user.getLoginName(), 
				dto.getPasswordProblem(), dto.getPasswordAnswer());*/
//		//判断密保是否正确
//		if(!checkPwdProblem(registerUserDTO)){
//			return "Secret security is not correct, modify fail!密保不正确，修改失败";
//		}
		String authKey = null;//user.getLoginName();
		//默认使用手机验证，前台也有类似的这个判断是手机还是邮件
		if (StringUtils.hasLength(user.getMobile())) {
			authKey = user.getMobile();
		}else if (StringUtils.hasLength(user.getEmail())) {
			authKey = user.getEmail();
		}
		//判断验证码是否之有效
		ActivationCode ac = activationCodeService.authVerificationCode(authKey, dto.getAuthCode(), "ChangeInfo");
		if ( ac != null ) {
			RegUserBasicDTO.dto2entity(dto, user);
			//如果验证通过,使用新号码覆盖旧号码(如果手机号码没有修改，字段dto.NewMobile 与 user.mobile 字段值会一致,所以功能上不会影响)
			if (StringUtils.hasText(dto.getNewMobile())) {
				user.setMobile(dto.getNewMobile());
			}
			//如果提交的数据中包含新密保答案，说明需要修改密保
	//		if ( dto.getNewPwdAnswer() != null && StringUtils.hasText(dto.getNewPwdAnswer())) {
	//			user.setPasswordProblem( dto.getNewPwdProblem() );
	//			user.setPasswordAnswer( dto.getNewPwdAnswer() );
	//		}
			/*String pa = user.getPasswordAnswer();
			dto.dto2entity(dto, user);
			if(!StringUtils.hasText(dto.getPasswordAnswer())){
				user.setPasswordAnswer(pa);
			}*/
			registerUserDAO.merge(user);
			
			ac.setStatus("已使用");
			activationCodeDAO.merge(ac);
			
			return "人个资料已修改成功!";
		}else{
			return "更新失败，验证码不正确!";
		}
	}
	
	//查询账户信息
	@Transactional
	public AccountDTO findAccountByLoginName(String loginName){
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", loginName);
		Account ac = regUser.getAccount();
		AccountDTO acDTO = new AccountDTO();
		acDTO.entity2dto(ac, acDTO);
		return acDTO;
	}
	
	/**
	 *  验证找回密码的问题是否正确
	 * @param rubDTO 找回密码的信息
	 * @return 是否正确
	 */
	@Transactional
	public 	String checkGetBackInfo(RegUserBasicDTO rubDTO,RegisterUserDTO registerUserDTO,String level){

		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", rubDTO.getLoginName());
		if(regUser!=null){
			registerUserDTO.setLoginName(rubDTO.getLoginName());
			if( checkPwdProblem( registerUserDTO) ){
				updatePassword(registerUserDTO,level);
				return "Password successfully(密码找回成功)!";
			}else{
				return "Secret answer is not correct(密保答案不正确)!";
			}
		}else{
			return "User does not exist(用户不存在)!";
		}
		
	}
	
	/**
	 * 校验用户的密保问题是否正确；
	 * @param regDTO
	 * @return
	 */
	public boolean checkPwdProblem(RegisterUserDTO regDTO){
		boolean bol = false;
		if (regDTO == null || regDTO.getLoginName() == null 
				|| regDTO.getPasswordProblem() == null || regDTO.getPasswordAnswer() == null
				) {
			return bol;
		}
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", regDTO.getLoginName());
		if(regUser!=null && regDTO.getPasswordProblem().equals(regUser.getPasswordProblem()) 
				&& regDTO.getPasswordAnswer().equals(regUser.getPasswordAnswer()) //判断问题答案是否正确
				){
			bol = true;
		}
		return bol;
	}
	
	@Transactional
	public String findPasswordByMobile(RegisterUserDTO registerUserDTO){
		
		//判断验证码是否之有效
		ActivationCode ac =activationCodeService.authVerificationCode(registerUserDTO.getLoginName(), registerUserDTO.getAuthCode(), "FindPassword");
		if ( ac!=null ) {
			RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", registerUserDTO.getLoginName());
			if(regUser!=null){
				if(StringUtils.hasText(registerUserDTO.getPassword1())){
					regUser.setPassword1(registerUserDTO.getPassword1());
				}
				if(StringUtils.hasText(registerUserDTO.getPassword2())){
					regUser.setPassword2(registerUserDTO.getPassword2());
				}
				registerUserDAO.merge(regUser);
				
				ac.setStatus(IActivationCodeService.USED);
				ac.setLastUpdateTime(new Date());
				activationCodeDAO.merge(ac);
				
				return "恭喜,密码找回成功!  <a href='login.jsp'>&gt;&gt;会员登入</a>";
			}else{
				return "对不起，您输入的账号不存在!";
			}
			
		}else{
			return "对不起，您输入的验证码不正确!";
		}
		
	}
	
	/**
	 * 交易密码验证
	 * @param loginName
	 * @param password
	 * @return
	 */
	@Transactional
	public boolean password3Valid(String loginName,String password){
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", loginName);
		if(regUser!=null && regUser.getPassword3().equals(password)){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 交易密码验证
	 * @param loginName
	 * @param password
	 * @return
	 */
	@Transactional
	public boolean password2Valid(String loginName,String password){
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", loginName);
		if(regUser!=null && regUser.getPassword2().equals(password)){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 修改一级、二级、三级密码
	 * @param dto
	 */
	@Transactional
	public String changePassword(RegisterUserDTO dto){
		boolean result = false;
		String errorMsg = null;
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", dto.getLoginName());
		if (dto != null && dto.getAuthType() != null
				&& dto.getAuthType().equals("2")) {//手机验证码的方式
			//判断验证码是否之有效
			ActivationCode ac = activationCodeService.authVerificationCode(regUser.getLoginName(), dto.getAuthCode(), "UpdatePassword");
			if (result = (ac != null) ) {//为true时验证通过
				ac.setStatus("已使用");
				activationCodeDAO.merge(ac);
				dto.setOldPassword1(regUser.getPassword1());//验证通过，手动设置旧密码，后面有验证条件
				dto.setOldPassword2(regUser.getPassword2());//验证通过，手动设置旧密码，后面有验证条件
			}else{
				errorMsg = "验证码不正确!";
			}
		}else{//原密码方式
			switch (checkInputParam(dto, regUser)) {
			case 1:
				errorMsg = "当前密码（登录密码）输入不正确，请检查输入!";
				break;
			case 2:
				errorMsg = "当前密码（交易密码）输入不正确，请检查输入!";
				break;
			default:
				result = true;
				break;
			}
		}
		if ( result ) {
			//RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", dto.getLoginName());
//			//判断密保是否正确
//			if(!StringUtils.hasLength(dto.getPasswordProblem()) 
//					|| !StringUtils.hasLength(dto.getPasswordAnswer())
//					|| !dto.getPasswordProblem().equals(regUser.getPasswordProblem())
//					|| !dto.getPasswordAnswer().equals(regUser.getPasswordAnswer())){
//				return "Secret security is not correct, modify fail!密保不正确，修改失败";
//			}
			if ( StringUtils.hasText(dto.getOldPassword1()) //如果dto.password1有输入，才需要修改
					&& StringUtils.hasText(dto.getPassword1())) {
				regUser.setPassword1(dto.getPassword1());
			}
			if (StringUtils.hasText(dto.getOldPassword2()) //如果dto.password2有输入，才需要修改
					&& StringUtils.hasText(dto.getPassword2())) {
				regUser.setPassword2(dto.getPassword2());
			}
			if (StringUtils.hasText(dto.getPassword3())) {
				regUser.setPassword3(dto.getPassword3());
			}
			registerUserDAO.merge(regUser);
			
			return "密码修改成功!";
			
		}else{
			//return "Phone verification code is not correct(验证码不正确)!";
		}
		return errorMsg;
	}
	private int checkInputParam(RegisterUserDTO dto,RegisterUser regUser){
		boolean r1 = false,r2 = false;
		if ( regUser != null && regUser.getRegisterUserId() > 0) {
			if ( !StringUtils.hasText(dto.getOldPassword1())//如果dto.password1有输入，才需要验证
					|| (StringUtils.hasText(regUser.getPassword1()) 
						&& dto.getOldPassword1().equals(regUser.getPassword1()))
						) {
				r1 = true;
			}
			if ( !StringUtils.hasText(dto.getOldPassword2()) //如果dto.password2有输入，才需要验证
				|| (StringUtils.hasText(regUser.getPassword2()) 
						&& dto.getOldPassword2().equals(regUser.getPassword2()))
						) {
				r2 = true;
			}
		}
		if (!r1) {
			return 1;
		}else if(!r2){
			return 2;
		}else{
			return 0;
		}
	}
	/**
	 * 修改一级、二级、密保
	 * @param dto
	 */
	@Transactional
	public String changePasswordByAdmin(RegisterUserDTO dto){
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", dto.getLoginName());
		regUser.setPasswordProblem(dto.getPasswordProblem());
		regUser.setPasswordAnswer(dto.getPasswordAnswer());
		regUser.setPassword1(dto.getPassword1());
		regUser.setPassword2(dto.getPassword2());
		regUser.setPassword3(dto.getPassword3());
		registerUserDAO.merge(regUser);
		return "Password changed successfully!密码修改成功!";
	}
	
	/**
	 * 分页查询直推用户
	 * @param qdto
	 * @param sord
	 * @param sidx
	 * @return
	 */
	@Transactional
	public PageDTO findDirectPushUserPager(RegisterUserQueryDTO qdto, String sord, String sidx){
		PageDTO p = registerUserDAO.findDirectPushUserPager(qdto, sord, sidx);
		List<RegisterUser> registerUsers = (List<RegisterUser>) p.getData();
		List<RegisterUserGridDTO> userDTOList = new ArrayList<RegisterUserGridDTO>(registerUsers.size());
		for(RegisterUser registerUser:registerUsers){
			//System.out.println(regiserUser.getRegisterLevel());
			RegisterUserGridDTO dto = new RegisterUserGridDTO();
			dto.setRegisterUserId(registerUser.getRegisterUserId());
			dto.setLoginName(registerUser.getLoginName());
			dto.setRegisterTime(registerUser.getRegisterTime());
			dto.setRegisterLevel(registerUser.getRegisterLevel());
			dto.setRegisterMoney(registerUser.getRegisterMoney());
			dto.setStatus(registerUser.getStatus());
			dto.setAsUserName(registerUser.getUserName());
			dto.setUserName(registerUser.getUserName().substring(0, 1)+"**");
			userDTOList.add(dto);
		}
		p.setData(userDTOList); 
		return p;
	}
	
	@Transactional
	public String login(String loginName,String password){
		List<RegisterUser> registerUsers = registerUserDAO.userValidate(loginName, password, "password1");
		if(registerUsers!=null && registerUsers.size()>0){
			RegisterUser entity = registerUsers.get(0);
			
			if("1".equals(entity.getUserStatus())){
				return "LoginNameAlreadyLock";
			}
			/*if(StringUtils.hasText(entity.getParentAccount()) || !"Activation".equals(entity.getStatus())){
				return "LoginNameOrPasswordError"; 
			}*/
			//if(entity!=null && !"Activation".equals(entity.getStatus()) && !"L1".equals(entity.getRegisterLevel()) ){
			if(entity!=null && StringUtils.hasText(entity.getLoginName())){
				sessionInit( entity );
				return "success";
			}
		}
			
		return "LoginNameOrPasswordError"; 
	}
	private void sessionInit(RegisterUser entity){
		HttpSession session = ServletActionContext.getRequest().getSession();
//		ServletContext sctx = session.getServletContext();
//		Map<String, HttpSession> sessionMap=null;
//
//		if(sctx!=null && sctx.getAttribute("sessionMap")!=null){
//			sessionMap=(HashMap<String, HttpSession>)sctx.getAttribute("sessionMap");
//			if(sessionMap.get(entity.getLoginName())!=null){//在别的地方登录，强迫下线
//				
//				HttpSession oldSession=(HttpSession)sessionMap.get(entity.getLoginName());
//				if(oldSession!=null){
//					try {
//						oldSession.invalidate();
//					} catch (Exception e){
//					}
//				}
//				sessionMap.remove(entity.getLoginName());
//			}
//		}else{
//			sessionMap=new HashMap<String, HttpSession>();
//		}
//		//用户重新放入Map
//		sessionMap.put(entity.getLoginName(),session);
//		sctx.setAttribute("sessionMap", sessionMap);
		session.setAttribute("loginName", entity.getLoginName());
		session.setAttribute("userName", entity.getUserName());
		session.setAttribute("registerLevel", entity.getRegisterLevel());
		session.setAttribute("email", entity.getEmail());
		session.setAttribute("mobile", entity.getMobile());
		session.setAttribute("registerTime", entity.getRegisterTime());
		session.setAttribute("registerUserId", entity.getRegisterUserId());
		session.setAttribute("declarationCenter", entity.isDeclarationCenter());
		session.setAttribute("activationTime", entity.getActivationTime());
		String linkCodeStart = "NA";
		/*if(entity.getLinkcode().startsWith("0000525954707599")){
			linkCodeStart = "0000525954707599";
		}
		if(entity.getLinkcode().startsWith("0000525954022335")){
			linkCodeStart = "0000525954022335";
		}
		if(entity.getLinkcode().equals("0000525954")){
			linkCodeStart = "0000525954";
		}*/
	
		session.setAttribute("regUserStatus", entity.getStatus());
		session.setAttribute("linkCodeStart",linkCodeStart);
		session.setAttribute("userEntity", entity);

	}
	
	@Transactional
	public boolean login2(String loginName,String password){
		List<RegisterUser> registerUsers = registerUserDAO.userValidate(loginName, password, "password2");
		if(registerUsers!=null && registerUsers.size()>0 && password.equals(registerUsers.get(0).getPassword2())){
			HttpSession session = ServletActionContext.getRequest().getSession();
			session.setAttribute("password2", "true");
			return true;
		}else{
			return false;
		}
	}
	@Transactional
	public List<RegisterUser> lastActiveUser(Date startTime){
		return registerUserDAO.lastActiveUser(startTime);
	};
	
	@Transactional
	public String findUserNameByLoginName(String loginName){
		RegisterUser user =registerUserDAO.findUniqueBy("loginName", loginName);
		if(user!=null)
			return user.getUserName();
		else
			return "";
	}
	
	/**
	 * 申请运营中心
	 * @param loginName
	 * @return
	 */
	@Transactional
	public void applyDeclarationCenter(String loginName){
		RegisterUser user =registerUserDAO.findUniqueBy("loginName", loginName);
		user.setApplyDeclarationCenter("待开通");
		registerUserDAO.merge(user);
	}

	/**
	 * 开通运营中心
	 * @param loginName
	 * @return
	 */
	@Transactional
	public void openOrCloseDeclarationCenter(String loginName){
		RegisterUser user =registerUserDAO.findUniqueBy("loginName", loginName);
		if("待开通".equals(user.getApplyDeclarationCenter())){
			user.setDeclarationCenter(true);
			user.setApplyDeclarationCenter("已开通");
		}else{
			user.setDeclarationCenter(false);
			user.setApplyDeclarationCenter("待开通");
		}
		registerUserDAO.merge(user);
	}
	
	
	
	
	
	
	//运营中心提成(运营中心：达标10万且完成9个直推的会员可以申请保单中心   3%提成)
	@Transactional
	public void baoDanZhongAward(String acLoginName){
		//激活会员
		RegisterUser user = registerUserDAO.findUniqueBy("loginName", acLoginName);
		if(user!=null && user.getDeclarationCenters()!=null){
			//运营中心
			RegisterUser declarationCenters = registerUserDAO.findUniqueBy("loginName", user.getDeclarationCenters());
			RuleDTO ruleDTO = ruleService.findRuleInfo();
			Double award = RuleDTO.level.get(user.getRegisterLevel())*ruleDTO.getRule037().doubleValue()/100;
			if(award>0){
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(declarationCenters.getLoginName());
				tr.setTransactionObject(acLoginName);
				tr.setTransactionType(TranType.BaoDanZhongXinTiCheng);
				tr.setRemark("");
				transactionRecordService.updateTran(tr, "Dynamic", award*0.7, ADD);

				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(declarationCenters.getLoginName());
				tr1.setTransactionObject(acLoginName);
				tr1.setTransactionType(TranType.BaoDanZhongXinTiCheng);
				tr1.setRemark("");
				transactionRecordService.updateTran(tr1, "Static", award*0.3, ADD);
			}
			
		}
		
	}
	//极差(完成直推9单)
	@Transactional
	public void jiChaAward(String acLoginName){
		RegisterUser user =registerUserDAO.findUniqueBy("loginName", acLoginName);
		List<RegisterUser>  users = registerUserDAO.findJiCha(user.getLinkcode(),new String[]{"579517","187500","809074","118826","027963","574124","177145"});
		List<RegisterUser> leaerUser = registerUserDAO.findJiChaLeader(user.getLinkcode(),new String[]{"579517","187500","809074","118826","027963","574124","177145"});
		users.addAll(leaerUser);
		System.out.println("极差:"+users.size());
		Map<String,List<String>> maps = new HashMap<String, List<String>>();
		List<String> fuser = new ArrayList<String>();
		for(RegisterUser u : users){
			Integer count = registerUserDAO.userCount(u.getLoginName(),"TeamActivation",new String[]{});
			System.out.println(u.getLoginName()+"团队人数："+count);
			Double totals = count*EVERY_SINGLE_SIZE;
			String leaderNo = u.getLoginName();
			
			if("027963".equals(leaderNo) 
					|| "574124".equals(leaderNo) 
					|| "177145".equals(leaderNo)){//这三领导号如果没有达到200万的，直接给他以200万始的奖金
				if(totals<2000000){
					totals = 2000000D;
				}
			}
			
			if("579517".equals(leaderNo) 
					|| "187500".equals(leaderNo) 
					|| "809074".equals(leaderNo) 
					|| "118826".equals(leaderNo)){//这四领导号如何没有达到1000万的，直接给他以1000万始的奖金
				if(totals<10000000){
					totals = 10000000D;
				}
			}
			if(totals>=1000000 && totals<2000000){//享受新增业绩4%
				fuser = maps.get("W100");
				if(fuser==null){
					fuser = new ArrayList<String>();
				}
				fuser.add(u.getLoginName());
				maps.put("W100",fuser);
			}else if(totals>=2000000 && totals<6000000){//享受新增业绩8%
				fuser = maps.get("W200");
				if(fuser==null){
					fuser = new ArrayList<String>();
				}
				fuser.add(u.getLoginName());
				maps.put("W200",fuser);
			}else if(totals>=6000000 && totals<10000000){//享受新增业绩11%
				fuser = maps.get("W600");
				if(fuser==null){
					fuser = new ArrayList<String>();
				}
				fuser.add(u.getLoginName());
				maps.put("W600",fuser);
			}else if(totals>=10000000 && totals<20000000){//享受新增业绩14%
				fuser = maps.get("W1000");
				if(fuser==null){
					fuser = new ArrayList<String>();
				}
				fuser.add(u.getLoginName());
				maps.put("W1000",fuser);
			}else if(totals>=20000000 && totals<40000000){//享受新增业绩17%
				fuser = maps.get("W2000");
				if(fuser==null){
					fuser = new ArrayList<String>();
				}
				fuser.add(u.getLoginName());
				maps.put("W2000",fuser);
			}else if(totals>=1000000 && totals>=40000000){//享受新增业绩20%
				fuser = maps.get("W4000");
				if(fuser==null){
					fuser = new ArrayList<String>();
				}
				fuser.add(u.getLoginName());
				maps.put("W4000",fuser);
			}
		}
		/**
		*1  总业绩达100万，小部门至少10万业绩，享受新增业绩4%
		*2、总业绩达200万, 小部门至少20万业绩，享受新增业绩8%           运营中心提升至3.5%
		*3、总业绩达到600万，小部门至少50万业绩,享受新增业绩11%         运营中心提升至4%
		*4、总业绩达到1000万，小部门至少100万业绩,享受新增业绩14%       运营中心提升至4.5%                       
		*5、总业绩达到2000万，第三个部门至少10万业绩，享受新增业绩17%。 运营中心提升至5%.
		*6、总业绩达到4000万，第三个部门至少200万业绩，享受新增业绩20%。运营中心提升至5.5%
		 */
		int W100Falg = 0;
		int W200Falg = 0;
		int W600Falg = 0;
		int W1000Falg = 0;
		int W2000Falg = 0;
		int W4000Falg = 0;
		if(maps.get("W100")!=null && maps.get("W100").size()>0){
			String strs = maps.get("W100").get(0);
			if(teamNumber(strs,100000D,2,acLoginName)){
				W100Falg =4;
				System.out.println("总业绩达100万，小部门至少10万业绩，享受新增业绩4%:::"+maps.get("W100").get(0));
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(strs);
				tr.setTransactionObject(acLoginName);
				tr.setTransactionType(TranType.POORBONUS);
				tr.setRemark("总业绩达100万，小部门至少10万业绩，享受新增业绩4%");
				transactionRecordService.updateTran(tr, "Dynamic", EVERY_SINGLE_SIZE*W100Falg/100D*0.7, ADD);

				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(strs);
				tr1.setTransactionObject(acLoginName);
				tr1.setTransactionType(TranType.POORBONUS);
				tr1.setRemark("总业绩达100万，小部门至少10万业绩，享受新增业绩4%; (30%)");
				transactionRecordService.updateTran(tr1, "Static", EVERY_SINGLE_SIZE*W100Falg/100D*0.3, ADD);
			}
			
		}
		if(maps.get("W200")!=null && maps.get("W200").size()>0){
			String strs = maps.get("W200").get(0);
			if(teamNumber(strs,200000D,2,acLoginName)){
				W200Falg = 8-W100Falg;
				System.out.println("总业绩达200万, 小部门至少20万业绩，享受新增业绩8% :::"+maps.get("W200").get(0));
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(strs);
				tr.setTransactionObject(acLoginName);
				tr.setTransactionType(TranType.POORBONUS);
				tr.setRemark("总业绩达200万, 小部门至少20万业绩，享受新增业绩8%");
				transactionRecordService.updateTran(tr, "Dynamic", EVERY_SINGLE_SIZE*W200Falg/100D*0.7, ADD);

				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(strs);
				tr1.setTransactionObject(acLoginName);
				tr1.setTransactionType(TranType.POORBONUS);
				tr1.setRemark("总业绩达200万, 小部门至少20万业绩，享受新增业绩8%; (30%)");
				transactionRecordService.updateTran(tr1, "Static", EVERY_SINGLE_SIZE*W200Falg/100D*0.3, ADD);
			}

		}
		if(maps.get("W600")!=null  && maps.get("W600").size()>0){
			String strs = maps.get("W600").get(0);
			if(teamNumber(strs,500000D,2,acLoginName)){
				W600Falg = 11-W200Falg-W100Falg;
				System.out.println("总业绩达到600万，小部门至少50万业绩,享受新增业绩11% :::"+maps.get("W600").get(0));
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(strs);
				tr.setTransactionObject(acLoginName);
				tr.setTransactionType(TranType.POORBONUS);
				tr.setRemark("总业绩达到600万，小部门至少50万业绩,享受新增业绩11%");
				transactionRecordService.updateTran(tr, "Dynamic", EVERY_SINGLE_SIZE*W600Falg/100D*0.7, ADD);

				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(strs);
				tr1.setTransactionObject(acLoginName);
				tr1.setTransactionType(TranType.POORBONUS);
				tr1.setRemark("总业绩达到600万，小部门至少50万业绩,享受新增业绩11%; (30%)");
				transactionRecordService.updateTran(tr1, "Static", EVERY_SINGLE_SIZE*W600Falg/100D*0.3, ADD);
			}

		}
		if(maps.get("W1000")!=null && maps.get("W1000").size()>0){
			String strs = maps.get("W1000").get(0);
			if("579517".equals(strs) 
					|| "187500".equals(strs) 
					|| "809074".equals(strs) 
					|| "118826".equals(strs) 
					|| teamNumber(strs,1000000D,2,acLoginName)){
				W1000Falg = 14-W600Falg-W200Falg-W100Falg;
				System.out.println("总业绩达到1000万，小部门至少100万业绩,享受新增业绩14% :::"+maps.get("W1000").get(0));
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(strs);
				tr.setTransactionObject(acLoginName);
				tr.setTransactionType(TranType.POORBONUS);
				tr.setRemark("总业绩达到1000万，小部门至少100万业绩,享受新增业绩14%");
				transactionRecordService.updateTran(tr, "Dynamic", EVERY_SINGLE_SIZE*W1000Falg/100D*0.7, ADD);
				
				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(strs);
				tr1.setTransactionObject(acLoginName);
				tr1.setTransactionType(TranType.POORBONUS);
				tr1.setRemark("总业绩达到1000万，小部门至少100万业绩,享受新增业绩14%; (30%)");
				transactionRecordService.updateTran(tr1, "Static", EVERY_SINGLE_SIZE*W1000Falg/100D*0.3, ADD);
			}
			

		}
		if(maps.get("W2000")!=null && maps.get("W2000").size()>0){
			String strs = maps.get("W2000").get(0);
			if("579517".equals(strs) 
					|| "187500".equals(strs) 
					|| "809074".equals(strs) 
					|| "118826".equals(strs) 
					|| teamNumber(strs,100000D,3,acLoginName)){
				W2000Falg = 17-W1000Falg-W600Falg-W200Falg-W100Falg;
				System.out.println("总业绩达到2000万，第三个部门至少10万业绩，享受新增业绩17% :::"+maps.get("W2000").get(0));
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(strs);
				tr.setTransactionObject(acLoginName);
				tr.setTransactionType(TranType.POORBONUS);
				tr.setRemark("总业绩达到2000万，第三个部门至少10万业绩，享受新增业绩17%");
				transactionRecordService.updateTran(tr, "Dynamic", EVERY_SINGLE_SIZE*W2000Falg/100D*0.7, ADD);

				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(strs);
				tr1.setTransactionObject(acLoginName);
				tr1.setTransactionType(TranType.POORBONUS);
				tr1.setRemark("总业绩达到2000万，第三个部门至少10万业绩，享受新增业绩17%; (30%)");
				transactionRecordService.updateTran(tr1, "Static", EVERY_SINGLE_SIZE*W2000Falg/100D*0.3, ADD);
			}

		}
		if(maps.get("W4000")!=null && maps.get("W4000").size()>0){
			//查询我团队下有没有达标
			String strs = maps.get("W4000").get(0);
			if("579517".equals(strs) 
					|| "187500".equals(strs) 
					|| "809074".equals(strs) 
					|| "118826".equals(strs) 
					|| teamNumber(strs,2000000D,3,acLoginName)){
				W4000Falg = 20-W2000Falg-W1000Falg-W600Falg-W200Falg-W100Falg;
				System.out.println("总业绩达到4000万，第三个部门至少200万业绩，享受新增业绩20%:::"+maps.get("W4000").get(0));	
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(strs);
				tr.setTransactionObject(acLoginName);
				tr.setTransactionType(TranType.POORBONUS);
				tr.setRemark("总业绩达到4000万，第三个部门至少200万业绩，享受新增业绩20%");
				transactionRecordService.updateTran(tr, "Dynamic", EVERY_SINGLE_SIZE*W4000Falg/100D*0.7, ADD);

				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(strs);
				tr1.setTransactionObject(acLoginName);
				tr1.setTransactionType(TranType.POORBONUS);
				tr1.setRemark("总业绩达到4000万，第三个部门至少200万业绩，享受新增业绩20%; (30%)");
				transactionRecordService.updateTran(tr1, "Static", EVERY_SINGLE_SIZE*W4000Falg/100D*0.3, ADD);
			}
		}	
	}
	
	//查找某个团队是否有指定业绩的数量
	@Transactional
	public boolean teamNumber(String loginName,Double top,int quy,String notInLoginName){
		//我的直推第一
		List<Object[]> lists = registerUserDAO.teamNumber(loginName,notInLoginName);
		if(lists!=null && lists.size()>=quy){
			Long[]  arr = new Long[lists.size()];
			int i = 0;
			for(Object[] obj : lists){
				//System.out.println(">>>>>"+(String)obj[0]+"---"+(Long)obj[1]);
				arr[i] = (Long)obj[1];
				i++;
			}
			arr = descSort(arr);
			//System.out.println("业绩："+top+"，部门："+quy+"，人数"+arr[quy-1]);
			if(arr[quy-1]*EVERY_SINGLE_SIZE>=top){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
		
	}
	public static Long[] descSort(Long[] param) {
		int in, out;
		Long temp = 0L;
		for (out = 0; out < param.length; out++) {
			for (in = param.length - 1; in > out; in--) {
				if (param[in] > param[in - 1]) {
					temp = param[in];
					param[in] = param[in - 1];
					param[in - 1] = temp;
				}
			}
		}
		return param;
	}
	//子用户激活
	@Transactional
	private String subUserActivate(String loginName){
		//得到当前用户
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName",loginName);
		if(regUser==null || "Activation".equals(regUser.getStatus())){
			return "AlreadyActivation";
		}
		//父帐户余额是否足够
		Double balance = transactionRecordService.findUserBalance(regUser.getParentAccount(), "Static");
		String registerLevel = regUser.getRegisterLevel();
		if(balance>=RuleDTO.level.get(registerLevel)){
			//扣除父帐户
			TransactionRecord tr = new TransactionRecord();
			tr.setLoginName(regUser.getParentAccount());
			tr.setTransactionObject(loginName);
			tr.setTransactionType(TranType.ZiZhangHaoJiHuoHouChu);
			transactionRecordService.updateTran(tr, "Static", RuleDTO.level.get(registerLevel).doubleValue(), CUT);
			
			regUser.setActivationTime(new Date());
			regUser.setStatus("Activation");
		}else{
			return "failure";
		}
		return "success";
	}
	/**
	 * 会员激活
	 * loginName激活用户
	 * 激活类型(自己激活，报单中心激活,推荐人激活)
	 */
	@Transactional
	public synchronized String userActivate(String loginName,String activeType){
		//得到当前用户
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName",loginName);
		if(regUser==null || "Activation".equals(regUser.getStatus())){
			return "AlreadyActivation";
		}
		//检查运营中心余额是否足够
		Double balance = 0D; 
		String cutuser = loginName;
		if("DeclarationCenters".equals(activeType)){
			balance = transactionRecordService.findUserBalance(regUser.getDeclarationCenters(), "Dynamic");
			cutuser = regUser.getDeclarationCenters();
		}else if("RecommendUser".equals(activeType)){
			balance = transactionRecordService.findUserBalance(regUser.getRecommendUser(), "Dynamic");
			cutuser = regUser.getRecommendUser();
		}else if("Myself".equals(activeType)){
			balance = transactionRecordService.findUserBalance(loginName, "Dynamic");
			cutuser = loginName;
		}
		String registerLevel = regUser.getRegisterLevel();
		if(balance>=RuleDTO.level.get(registerLevel)){
			//扣除开通费用
			TransactionRecord tr = new TransactionRecord();
			tr.setLoginName(cutuser);
			tr.setTransactionObject(loginName);
			tr.setTransactionType(TranType.HuiYuanKaiTongKouChu);
			transactionRecordService.updateTran(tr, "Dynamic", RuleDTO.level.get(registerLevel).doubleValue(), CUT);
			
			regUser.setActivationTime(new Date());
			//推荐数统计
			RegisterUser recommendUser = registerUserDAO.findUniqueBy("loginName",regUser.getRecommendUser());
			recommendUser.setRecommendQuantity(recommendUser.getRecommendQuantity()+1);
			regUser.setStatus("Activation");
			regUser.setActivationTime(new Date());
			//注册账户(80%)
			regUser.setTotalIncome(regUser.getRegisterMoney()+regUser.getRegisterMoney()*80/100);
			regUser.setIssued(regUser.getRegisterMoney()+regUser.getRegisterMoney()*80/100);
		
			TransactionRecord tr_rega = new TransactionRecord();
			tr_rega.setLoginName(regUser.getLoginName());
			tr_rega.setTransactionObject("System");
			tr_rega.setTransactionType(TranType.TouZiShouYi);
			transactionRecordService.updateTran(tr_rega, TranType.STATIC, regUser.getRegisterMoney()+regUser.getRegisterMoney()*0.8, TranType.ADD);
			
			
			RuleDTO ruleDTO = ruleService.findRuleInfo();
			//用户有效期
			Calendar ct = new GregorianCalendar(  );
			ct.setTime( new Date());
			ct.set(Calendar.DATE,ct.get(Calendar.DATE)+ruleDTO.getYifenghong2().intValue());
			regUser.setValidTime(ct.getTime());
			
			
			//直推奖
			System.out.println("----直推奖------");
			bonusService.directPush(loginName, ruleDTO);
			
			//管理奖
			System.out.println("----管理奖------");
			bonusService.activeUserAward(regUser, recommendUser, ruleDTO);

			//代数奖/领导奖
			System.out.println("----领导奖(根据代数或推荐来拿)------");
			bonusService.algebraicAward(ruleDTO,regUser, recommendUser,null, 0);
			
		}else{
			return "balance";
		}
		return "success";
	}
	
	//客户提成
	private void recommendAward(RuleDTO ruleDTO , RegisterUser regUser , RegisterUser recommendUser){
		
		if(recommendUser!=null && !"L1".equals(recommendUser.getRegisterLevel())){
			Double st = ruleDTO.getRule032();
			Double award = st*RuleDTO.level.get(regUser.getRegisterLevel()).doubleValue()/100;
			
			TransactionRecord tr = new TransactionRecord();
			tr.setLoginName(recommendUser.getLoginName());
			tr.setTransactionObject(regUser.getLoginName());
			tr.setTransactionType(TranType.ZhiTuiJiang);
			tr.setRemark("70%");
			transactionRecordService.updateTran(tr, "Dynamic", award*0.7, ADD);
			
			
			TransactionRecord tr1 = new TransactionRecord();
			tr1.setLoginName(recommendUser.getLoginName());
			tr1.setTransactionObject(regUser.getLoginName());
			tr1.setTransactionType(TranType.ZhiTuiJiang);
			tr1.setRemark("30%");
			transactionRecordService.updateTran(tr1, "Static", award*0.3, ADD);
		}
		
	}
	
	
	
	
	//会员充值与扣除
	@Transactional
	public String userRecharge(String dtype , Double moeny ,String loginName){
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName",loginName);
		if(regUser!=null){
			if("NotActivation".equals(regUser.getStatus())){//是否已激活
				return "Membership is not active, not allowed to recharge or deduction!(会员未激活，不允许充值或扣除!)";
			}else{
				String opttype = ADD;
				String acconttype = "";
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(loginName);
				tr.setTransactionObject("system");
				tr.setDtype("Dynamic");
				if("DynamicAdd".equals(dtype) || "payadd".equals(dtype)){
					opttype = ADD;
					acconttype = "Dynamic";
					if("payadd".equals(dtype)){
						tr.setRemark("在线充值");
					}
					tr.setTransactionType(TranType.ChongZhi);
				}else if("StaticAdd".equals(dtype)){
					opttype = ADD;
					acconttype = "Static";
					tr.setTransactionType(TranType.ChongZhi);
				}else if("DynamicRed".equals(dtype)){
					opttype = CUT;
					acconttype = "Dynamic";
					tr.setTransactionType(TranType.KouChu);
				}else if("StaticRed".equals(dtype)){
					opttype = CUT;
					acconttype = "Static";
					tr.setTransactionType(TranType.KouChu);
				}else{
					opttype = CUT;
					acconttype = "Recharge";
					tr.setTransactionType(TranType.KouChu);
				}
				transactionRecordService.updateTran(tr, acconttype, moeny, opttype);
			}
		}else{
			return "Member ID does not exist(会员ID不存在)!";
		}
		return "Recharge or deduction of success(充值或扣除成功)!";
	}
	
	
	//充值账户转动态或静态
	@Transactional
	public String rechargeToDs(String dtype , Double moeny ,String loginName){
		
		Double balance = transactionRecordService.findUserBalance(loginName, "Dynamic");
		if(moeny==null || moeny<10){
			return "To the amount of the input is not correct, please check, thank you(转入的金额输入不正确，请检查，谢谢)!";
		}if(moeny>balance){
			return "To the amount of greater balance, please check, thank you(转入的金额大于余额，请检查，谢谢)!";
		}else{
			//修改奖金钱包
			TransactionRecord tr = new TransactionRecord();
			tr.setLoginName(loginName);
			tr.setTransactionObject(loginName);
			tr.setTransactionType(TranType.TransferredDeclarationWallet);
			transactionRecordService.updateTran(tr, "Dynamic", moeny, CUT);
			
			
			//修改报单钱包
			TransactionRecord tr1 = new TransactionRecord();
			tr1.setLoginName(loginName);
			tr1.setTransactionObject(loginName);
			tr1.setTransactionType(TranType.TransferredDeclarationWallet);
			transactionRecordService.updateTran(tr1, "Static", moeny, ADD);
			
			return "To successfully, click on the following to return to the previous page(转入成功，点击以下退回上一页面)!";
		}
	}
	
	
	/**
	 * 分页查询我的团队
	 * @param qdto
	 * @param sord
	 * @param sidx
	 * @return
	 */
	@Transactional
	public PageDTO myTeamPager(RegisterUserQueryDTO qdto, String sord, String sidx){
		if(qdto!=null && qdto.getSessionUser()!=null){
			RegisterUser ru = registerUserDAO.findUniqueBy("loginName", qdto.getSessionUser());
			qdto.setLinkCode(ru.getLinkcode());
		}else{
			HttpSession session = ServletActionContext.getRequest().getSession();
			if(session.getAttribute("loginName")!=null){
				RegisterUser ru = registerUserDAO.findUniqueBy("loginName", session.getAttribute("loginName"));
				qdto.setLinkCode(ru.getLinkcode());
			}
		}
		PageDTO p = registerUserDAO.myTeamPager(qdto, sord, sidx);
		List<RegisterUser> registerUsers = (List<RegisterUser>) p.getData();
		List<RegisterUserGridDTO> userDTOList = new ArrayList<RegisterUserGridDTO>(registerUsers.size());
		for(RegisterUser registerUser:registerUsers){
			//System.out.println(regiserUser.getRegisterLevel());
			RegisterUserGridDTO dto = new RegisterUserGridDTO();
			dto.setLoginName(registerUser.getLoginName());
			dto.setRegisterTime(registerUser.getRegisterTime());
			dto.setRegisterLevel(registerUser.getRegisterLevel());
			dto.setStatus(registerUser.getStatus());
			dto.setAsUserName(registerUser.getUserName());
			dto.setUserName(registerUser.getUserName().substring(0, 1)+"**");
			userDTOList.add(dto);
		}
		p.setData(userDTOList);
		return p;
	}
	
	//今天推荐人数(TodayRec)
	//今天推荐并激活人数(TodayRecActivation)
	//推荐全部人数(AllRec)
	//推荐已激活人数(AllRecActivation)
	//我的团队总数(Team)
	//我的团队激活人数(TeamActivation)
	@Transactional
	public Integer userCount(String loginName,String type,String[] notInUser){
		return registerUserDAO.userCount(loginName, type,notInUser);
	}

	/**
	 * 统计团队业绩
	 * 100W,200W,600W,1000W,2000W,4000W,
	 */
	@Transactional
	public Map<String, List<String>> teamYeJiStat(RegisterUserQueryDTO queryDTO){
		Map<String,List<String>> maps = new HashMap<String, List<String>>();
		maps.put("W100", new ArrayList<String>());
		maps.put("W200", new ArrayList<String>());
		maps.put("W600", new ArrayList<String>());
		maps.put("W1000", new ArrayList<String>());
		maps.put("W2000", new ArrayList<String>());
		maps.put("W4000", new ArrayList<String>());
		if(queryDTO.getLoginName()!=null){
			RegisterUser user = registerUserDAO.findUniqueBy("loginName", queryDTO.getLoginName());
			if(user!=null){
				queryDTO.setLinkCode(user.getLinkcode());
			}
		}
		
		List<RegisterUser> rus = registerUserDAO.findRegUser(queryDTO);
		DecimalFormat df = (DecimalFormat)NumberFormat.getInstance();
		df.applyPattern("######.0");
		for(RegisterUser reg : rus){
			Integer count = registerUserDAO.userCount(reg.getLoginName(),"TeamActivation",null);
			Double totals = count*EVERY_SINGLE_SIZE;
			if(totals>=1000000 && totals<2000000){//享受新增业绩4%
				List<String> users = maps.get("W100");
				if(users==null){
					users = new ArrayList<String>();
				}
				users.add(reg.getLoginName()+",业绩："+df.format(totals));
				maps.put("W100",users);
			}else if(totals>=2000000 && totals<6000000){//享受新增业绩8%
				List<String> users = maps.get("W200");
				if(users==null){
					users = new ArrayList<String>();
				}
				users.add(reg.getLoginName()+",业绩："+df.format(totals));
				maps.put("W200",users);
			}else if(totals>=6000000 && totals<10000000){//享受新增业绩11%
				List<String> users = maps.get("W600");
				if(users==null){
					users = new ArrayList<String>();
				}
				users.add(reg.getLoginName()+",业绩："+df.format(totals));
				maps.put("W600",users);
			}else if(totals>=10000000 && totals<20000000){//享受新增业绩14%
				List<String> users = maps.get("W1000");
				if(users==null){
					users = new ArrayList<String>();
				}
				users.add(reg.getLoginName()+",业绩："+df.format(totals));
				maps.put("W1000",users);
			}else if(totals>=20000000 && totals<40000000){//享受新增业绩17%
				List<String> users = maps.get("W2000");
				if(users==null){
					users = new ArrayList<String>();
				}
				users.add(reg.getLoginName()+",业绩："+df.format(totals));
				maps.put("W2000",users);
			}else if(totals>=1000000 && totals>=40000000){//享受新增业绩20%
				List<String> users = maps.get("W4000");
				if(users==null){
					users = new ArrayList<String>();
				}
				users.add(reg.getLoginName()+",业绩："+df.format(totals));
				maps.put("W4000",users);
			}
		}
		return maps;
	}
	
	/**
	 * 系统初始化
	 */
	
	public void initSystemData(){
		//删除历史操作记录
		transactionRecordDAO.deleteAll();
		
		//删除在线支付记录 
		orderDAO.deleteAll();
		//删除邮件验证
		activationCodeDAO.deleteAll();
		//删除提现申请
		extractDAO.deleteAll();
		matchDAO.deleteAll();
		sellDAO.deleteAll();
		buyDAO.deleteAll();
		generateRegisterCodeDao.deleteAll();
		//删除注册会员
		registerUserDAO.deleteAll();
		//添加系统账号0000
		RegisterUser entity = new RegisterUser();
		entity.setLoginName("S00001");
		entity.setPassword1("123456");
		entity.setPassword2("123456");
		entity.setUserName("system");
		entity.setRegisterLevel("L4");
		entity.setRegisterMoney(20000L);
		entity.setActivationTime(new Date());
		entity.setRegisterTime(new Date());
		entity.setStatus("Activation");
		entity.setEmail("system@ds.com");
		entity.setDeclarationCenter(true);
		entity.setRecommendQuantity(0);
		entity.setLinkcode("S00001");
		entity.setLevel(4L);
		registerUserDAO.save(entity);
		
		//制度规则
		RuleDTO ruleDTO = ruleService.findRuleInfo();
		ruleDTO.setRule001("平台正在分红中,请稍后......");
		ruleDTO.setRule002("平台中心");
		Calendar a=Calendar.getInstance();
		ruleDTO.setRule009("Copyright © "+a.get(Calendar.YEAR)+" Web ");
		ruleDTO.setRule012(10L);
		ruleDTO.setRule013(10L);
		ruleDTO.setRule010("每天只允许提交一次，100或100的倍数");
		
		ruleDTO.setRule015(3000D);//直推及管理奖账户释放金额
		ruleDTO.setRule016(7D);//代数及团队奖账户释放天数
		
		ruleDTO.setRule008("平台中心");
		ruleDTO.setRule003("smtp.qq.com");
		ruleDTO.setRule004("mail@qq.com");
		ruleDTO.setRule005("mail password");
		ruleDTO.setRule006("平台中心注册激活码");
		ruleDTO.setRule007("尊敬的用户，您好！平台中心注册激活码是:${code}!");
		//日分红
		ruleDTO.setYifenghong1(3D);
		ruleDTO.setYifenghong2(60D);
		
		//管理奖
		ruleDTO.setRule073(2D);
		
		//直推
		ruleDTO.setZhitui1(8D);
		ruleDTO.setZhitui2(10D);
		ruleDTO.setZhitui3(15D);
		ruleDTO.setZhitui4(20D);
		ruleDTO.setZhitui5(0D);
		ruleDTO.setZhitui6(0D);
		//对碰
		ruleDTO.setDuipeng1(6D);
		ruleDTO.setDuipeng2(7D);
		ruleDTO.setDuipeng3(8D);
		ruleDTO.setDuipeng4(10D);
		ruleDTO.setDuipeng5(12D);
		ruleDTO.setDuipeng6(0D);
		
		ruleDTO.setDuipeng7(500D);
		ruleDTO.setDuipeng8(2000D);
		ruleDTO.setDuipeng9(5000D);
		ruleDTO.setDuipeng10(10000D);
		ruleDTO.setDuipeng11(20000D);
		ruleDTO.setDuipeng12(0D);
		//见点奖
		ruleDTO.setFuwu1(5D);
		ruleDTO.setFuwu2(8D);
		ruleDTO.setFuwu3(12D);
		ruleDTO.setFuwu4(16D);
		ruleDTO.setFuwu5(20D);
		ruleDTO.setFuwu6(0D);
		
		ruleDTO.setFuwu7(0.5D);
		ruleDTO.setFuwu8(0.5D);
		ruleDTO.setFuwu9(0.5D);
		ruleDTO.setFuwu10(0.5D);
		ruleDTO.setFuwu11(0.5D);
		ruleDTO.setFuwu12(0D);
		
		//领导奖
		ruleDTO.setDaishu1(1D);
		ruleDTO.setDaishu2(2D);
		ruleDTO.setDaishu3(3D);
		ruleDTO.setDaishu4(3D);
		ruleDTO.setDaishu5(3D);
		ruleDTO.setDaishu6(0D);
		ruleDTO.setDaishu7(5D);
		ruleDTO.setDaishu8(3D);
		ruleDTO.setDaishu9(0.3D);
		ruleDTO.setDaishu10(0D);
		ruleDTO.setDaishu11(0D);
		ruleDTO.setDaishu12(0D);
		
		//服务中心奖
		ruleDTO.setFuwuzhongxin1(3D);
		
		ruleDTO.setDuipeng13("1111=1,2222=5");
		
		ruleDTO.setTimeOut1(24L);
		ruleDTO.setTimeOut1(48L);
		ruleDTO.setTimeOut1(48L);
		
		ruleService.editRule(ruleDTO);
	}
	
	
	
	/**
	 * 推荐树形图
	 * @param userNo
	 * @return
	 */
	@Transactional
	public XPTreeViewDTO findXPTree(String loginName,String lang){
		String teamStr = "Team";
		String statusStr = "Actived";
		String yejiStr = "Performance";
		String left = "Left";
		String right = "Right";
		String level = "Level";
		if("zh_CN".equals(lang)){
			teamStr = "团队";
			statusStr = "激活";
			yejiStr = "业绩";
			left = "左区";
			right = "右区";
			level = "等级";
		}
		RegisterUser user = registerUserDAO.findUniqueBy("loginName", loginName);
		XPTreeViewDTO treeViewDTO = new XPTreeViewDTO();
		Integer sum = userCount(loginName,"Team",null);
		Integer acsum = userCount(loginName,"TeamActivation",null);
		//treeViewDTO.getData().put("title", "["+user.getLoginName()+"]["+level+":"+user.getRegisterLevel()+"]["+teamStr+":"+sum+"]["+statusStr+":"+acsum+"]["+left+":"+user.getLeftSum()+"]["+right+":"+user.getRightSum()+"]");
		treeViewDTO.getData().put("title", "["+user.getLoginName()+"]["+level+":"+RuleDTO.levelName.get(user.getRegisterLevel())+"]["+teamStr+":"+sum+"]["+statusStr+":"+acsum+"]");
		//treeViewDTO.getData().put("title", "["+user.getLoginName()+"]["+teamStr+":"+sum+"]["+left+":"+user.getLeftSum()+"]["+right+":"+user.getRightSum()+"]");
		
		if("Activation".equals(user.getStatus()))
			treeViewDTO.getData().put("icon","../images/user_avatar.png");
		else
			treeViewDTO.getData().put("icon","../images/unofficialMember.gif");
		if(sum==1){
			treeViewDTO.setState("");
		}else{
			treeViewDTO.setState("open");
		}
		
		treeViewDTO.getAttr().put("loginName", user.getLoginName());
		getChildren(user,treeViewDTO,lang);
		return treeViewDTO;
		
	}
	
	@Transactional
	public void getChildren(RegisterUser user,XPTreeViewDTO treeViewDTO,String lang){
		String teamStr = "Team";
		String statusStr = "Actived";
		String yejiStr = "Performance";
		String left = "Left";
		String right = "Right";
		String level = "Level";
		if("zh_CN".equals(lang)){
			teamStr = "团队";
			statusStr = "激活";
			yejiStr = "业绩";
			left = "左区";
			right = "右区";
			level = "等级";
		}
		
		List<RegisterUser> users = (registerUserDAO.findBy("contactNo", user.getLoginName()));
		List<XPTreeViewDTO> xps = new ArrayList<XPTreeViewDTO>();
		if(users!=null && users.size()>0){
			if(users.size()>=2){
				for(RegisterUser u : users){
					XPTreeViewDTO dto = new XPTreeViewDTO();
					Integer sum = userCount(u.getLoginName(),"Team",null);
					Integer acsum = userCount(u.getLoginName(),"TeamActivation",null);
					//dto.getData().put("title", "["+u.getLoginName()+"]["+level+":"+u.getRegisterLevel()+"]["+teamStr+":"+sum+"]["+statusStr+":"+acsum+"]["+left+":"+u.getLeftSum()+"]["+right+":"+u.getRightSum()+"]");
					dto.getData().put("title", "["+u.getLoginName()+"]["+level+":"+RuleDTO.levelName.get(u.getRegisterLevel())+"]["+teamStr+":"+sum+"]["+statusStr+":"+acsum+"]");
					//dto.getData().put("title", "["+u.getLoginName()+"]["+teamStr+":"+sum+"]["+left+":"+u.getLeftSum()+"]["+right+":"+u.getRightSum()+"]");
					
					if("Activation".equals(u.getStatus()))
						dto.getData().put("icon","../images/user_avatar.png");
					else
						dto.getData().put("icon","../images/unofficialMember.gif");
					if(sum>1 || "Activation".equals(u.getStatus())){
						dto.setState("closed");
					}else{
						dto.setState("");
					}
					dto.getAttr().put("loginName", u.getLoginName());
					xps.add(dto);
				}
			}else{
				RegisterUser cu = users.get(0);
				
				XPTreeViewDTO dto = new XPTreeViewDTO();
				Integer sum = userCount(cu.getLoginName(),"Team",null);
				Integer acsum = userCount(cu.getLoginName(),"TeamActivation",null);
				//dto.getData().put("title", "["+cu.getLoginName()+"]["+level+":"+cu.getRegisterLevel()+"]["+teamStr+":"+sum+"]["+statusStr+":"+acsum+"]["+left+":"+cu.getLeftSum()+"]["+right+":"+cu.getRightSum()+"]");
				dto.getData().put("title", "["+cu.getLoginName()+"]["+level+":"+cu.getRegisterLevel()+"]["+teamStr+":"+sum+"]["+statusStr+":"+acsum+"]");
				
				//dto.getData().put("title", "["+cu.getLoginName()+"]["+teamStr+":"+sum+"]["+left+":"+cu.getLeftSum()+"]["+right+":"+cu.getRightSum()+"]");
				
				if("Activation".equals(cu.getStatus()))
					dto.getData().put("icon","../images/user_avatar.png");
				else
					dto.getData().put("icon","../images/unofficialMember.gif");
				if(sum>1){
					dto.setState("closed");
				}else{
					dto.setState("");
				}
				dto.getAttr().put("loginName", cu.getLoginName());
				xps.add(dto);
				
				
				/*XPTreeViewDTO dto1 = new XPTreeViewDTO();
				dto1.setState("");
				dto1.getData().put("title","右区(点击注册)");
				dto1.getData().put("icon","../images/newReg.gif");
				dto1.getAttr().put("contactNo",user.getLoginName());
				dto1.getAttr().put("registerLocation","bArea");
				dto1.getAttr().put("newReg","newReg");
				xps.add(dto1);*/
				
				//getChildren(cu,dto,lang);
			}
			treeViewDTO.setChildren(xps);
			
		}else{//如果没有就加两个空位
			if("Activation".equals(user.getStatus())){
				/*XPTreeViewDTO dto = new XPTreeViewDTO();
				dto.setState("");
				dto.getData().put("title","左区(点击注册)");
				dto.getData().put("icon","../images/newReg.gif");
				dto.getAttr().put("contactNo",user.getLoginName());
				dto.getAttr().put("registerLocation","aArea");
				dto.getAttr().put("newReg","newReg");
				xps.add(dto);
				
				
				XPTreeViewDTO dto1 = new XPTreeViewDTO();
				dto1.setState("");
				dto1.getData().put("title","右区(点击注册)");
				dto1.getData().put("icon","../images/newReg.gif");
				dto1.getAttr().put("contactNo",user.getLoginName());
				dto1.getAttr().put("registerLocation","bArea");
				dto1.getAttr().put("newReg","newReg");
				xps.add(dto1);
				treeViewDTO.setChildren(xps);*/
			}
			
		}
	}
	public String findUserPassword(String userName){
    	
    		RegisterUser user1=registerUserDAO.findUniqueBy("loginName", userName);
    		if(user1!=null && user1.getEmail()!=null){
    			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
    	    	AES aec=new AES();
    	    	String active="";
    			try {
    				active = aec.encrypt(sdf.format(new Date())+"="+userName);
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    	    	Calendar c = Calendar.getInstance();
    	        c.setTime(new Date());   //设置当前日期   
    	        c.add(Calendar.MINUTE, 10); //日期分钟加1,Calendar.DATE(天),Calendar.HOUR(小时)   
    	        Date date = c.getTime(); //结果  
    	        
    			Boolean result=emailService.sendMail(user1.getEmail(),"[XXX理财]找回密码",getEmailContent(userName,active,sdf.format(date)));
            	if(result){
            		return user1.getEmail();
            	}else{
            		return "emailSendError";
            	}
    		}else{
    			return "noUser";
    		}
    }
	public String getEmailContent(String userName,String active,String overDate){
    	String content="亲爱的"+userName+"：您好！<br>"
    +"&nbsp;&nbsp;&nbsp;&nbsp;您收到这封这封电子邮件是因为您 (也可能是某人冒充您的名义) 申请了一个新的密码。假如这不是您本人所申请, 请不用理会这封电子邮件, 但是如果您持续收到这类的信件骚扰, 请您尽快联络管理员。"
    +"<br>要使用新的密码, 请使用以下链接启用密码。"
    +"<br>http://localhost:8080/itsm-web/resetpassword?user="+userName+"&active="+active
    +"<br>(如果无法点击该URL链接地址，请将它复制并粘帖到浏览器的地址输入框，然后单击回车即可。该链接使用后将立即失效。)"
   +" <br>注意:请您在收到邮件1个小时内("+overDate+"前)使用，否则该链接将会失效。";
    	return content;
    }
	@Transactional
	public Boolean updateUserPassword(RegisterUserDTO dto){
		Boolean result=false;
		try{
			RegisterUser user1=registerUserDAO.findUniqueBy("loginName", dto.getLoginName());
			user1.setPassword1(dto.getPassword1());
			user1.setPassword2(dto.getPassword2());
			registerUserDAO.update(user1);
			result=true;
		}catch (Exception e) {
			e.printStackTrace();
			result=false;
		}
		return result;
	}
	/**
	 * 系谱图
	 * @param loginName
	 * @return
	 */
	public GenealogicalTreeDTO findGenealogy(String loginName){
		GenealogicalTreeDTO gtdto = new GenealogicalTreeDTO();
		//判断是否是我当前团队的
		if(isMyTream(loginName)){
			//构造第一层
			RegisterUser user=registerUserDAO.findUniqueBy("loginName",loginName);
			List<RegisterUserDTO> level1 = new ArrayList<RegisterUserDTO>();
			RegisterUserDTO dto = new RegisterUserDTO();
			entity2dto(user,dto);
			level1.add(dto);
			gtdto.setLevel1(level1);
			
			//构造第二层
			List<RegisterUserDTO> level2 = new ArrayList<RegisterUserDTO>();
			for(RegisterUserDTO rudto : level1){
				level2.addAll(gxp(rudto));
			}
			gtdto.setLevel2(level2);
//			for(RegisterUserDTO dd : level2){
//				System.out.println("第二层:"+dd.getLoginName());
//			}
			
			
			//构造第三层
			List<RegisterUserDTO> level3 = new ArrayList<RegisterUserDTO>();
			for(RegisterUserDTO rudto : level2){
				level3.addAll(gxp(rudto));
			}
			gtdto.setLevel3(level3);
//			for(RegisterUserDTO dd : level3){
//				System.out.println("第三层:"+dd.getLoginName());
//			}
			
			//构造第四层
			/*List<RegisterUserDTO> level4 = new ArrayList<RegisterUserDTO>();
			for(RegisterUserDTO rudto : level3){
				level4.addAll(gxp(rudto));
			}
			gtdto.setLevel4(level4);*/
			return gtdto;
		}else{
			return null;
		}
		
	}
	
	
	private List<RegisterUserDTO> gxp(RegisterUserDTO dto){
		List<RegisterUserDTO> dtos = new ArrayList<RegisterUserDTO>();
		//构造不可注册的空拉
		if( "NULL".equals(dto.getLoginName())
				|| "LEFT".equals(dto.getLoginName()) || "RIGHT".equals(dto.getLoginName())){
			RegisterUserDTO dto1 = new RegisterUserDTO();
			dto1.setLoginName("NULL");
			dtos.add(dto1);
			
			RegisterUserDTO dto2 = new RegisterUserDTO();
			dto2.setLoginName("NULL");
			dtos.add(dto2);
		}else{
			List<RegisterUser> list2 = registerUserDAO.findBy("contactNo", dto.getLoginName());
			if(list2.size()==0){
				RegisterUserDTO leftdto = new RegisterUserDTO();
				if("Activation".equals(dto.getStatus())){
					leftdto.setLoginName("LEFT");
				}else{
					//leftdto.setLoginName("NULL");
					leftdto.setLoginName("LEFT");
				}
				dtos.add(leftdto);
				
				RegisterUserDTO rightdto = new RegisterUserDTO();
				//rightdto.setLoginName("NULL");
				rightdto.setLoginName("RIGHT");
				dtos.add(rightdto);
			}else{
				if(list2.size()==1){
					if("aArea".equals(list2.get(0).getRegisterLocation())){
						for(RegisterUser entity : list2){
							RegisterUserDTO dto2 = new RegisterUserDTO();
							entity2dto(entity, dto2);
							dtos.add(dto2);
						}
						
						RegisterUserDTO rightdto = new RegisterUserDTO();
						if("Activation".equals(dto.getStatus())){
							rightdto.setLoginName("RIGHT");
						}else{
							//rightdto.setLoginName("NULL");
							rightdto.setLoginName("RIGHT");
						}
						dtos.add(rightdto);
					}else{
						RegisterUserDTO rightdto = new RegisterUserDTO();
						if("Activation".equals(dto.getStatus())){
							rightdto.setLoginName("LEFT");
						}else{
							//rightdto.setLoginName("NULL");
							rightdto.setLoginName("LEFT");
						}
						dtos.add(rightdto);
						
						for(RegisterUser entity : list2){
							RegisterUserDTO dto2 = new RegisterUserDTO();
							entity2dto(entity, dto2);
							dtos.add(dto2);
						}
					}
					
				}else{
					RegisterUserDTO dto1 = new RegisterUserDTO();
					RegisterUserDTO dto2 = new RegisterUserDTO();
					for(RegisterUser entity : list2){
						if("aArea".equals(entity.getRegisterLocation())){
							entity2dto(entity, dto1);
						}else{
							entity2dto(entity, dto2);
						}
						
						
					}
					dtos.add(dto1);
					dtos.add(dto2);
				}
			}
		}
		return dtos;
	}
	
	
	
	private void entity2dto(RegisterUser entity,RegisterUserDTO dto){
		dto.setLoginName(entity.getLoginName());
		dto.setUserName(entity.getUserName().substring(0, 1)+"**");
		dto.setStatus(entity.getStatus());
		dto.setRegisterLevel(entity.getRegisterLevel());
		dto.setLeftPoint(entity.getLeftPoint());
		dto.setRightPoint(entity.getRightPoint());
		dto.setLeftSum(entity.getLeftSum());
		dto.setRightSum(entity.getRightSum());
		dto.setSubAccount(entity.getSubAccount());
		dto.setContactNo(entity.getContactNo());
	}
	
	private boolean isMyTream(String loginName1){
		HttpSession session = ServletActionContext.getRequest().getSession();
		RegisterUser user=registerUserDAO.findUniqueBy("loginName",(String)session.getAttribute("loginName"));
		return registerUserDAO.isMyTeam(user.getLinkcode(), loginName1);
	}
	
	
	//修改推广报单中心
	@Transactional
	public void updateTuGuangDc(String loginName , String tuGuangDc){
		RegisterUser user=registerUserDAO.findUniqueBy("loginName",loginName);
		if(user!=null){
			user.setTuGuangDc(tuGuangDc);
			registerUserDAO.merge(user);
		}
	}
	
	@Transactional
	public String userUpgrade(RegisterUserDTO regUserDTO){
		RegisterUser user=registerUserDAO.findUniqueBy("loginName",regUserDTO.getLoginName());
		if(user==null){
			return "升级失败，所要升级会员不存在，请检查!";
		}else if("L7".equals(user.getRegisterLevel())){
			return "升级失败，已是最高级别无需再升级!";
		}else if(regUserDTO.getRegisterLevel().equals(user.getRegisterLevel())){
			return "升级失败，升级级别不能跟当前级别一致!";
		}else{
			
			//五星账号升级6星七星的 需要马币  其他1星省五星的用现金
			//余额
			Double balance = 0D;
			balance = transactionRecordService.findUserBalance(regUserDTO.getLoginName(), "Dynamic");
			if("L6".equals(regUserDTO.getRegisterLevel()) || "L7".equals(regUserDTO.getRegisterLevel())){
				balance = transactionRecordService.findUserBalance(regUserDTO.getLoginName(), "Static");
			}
			//当前级别
			String currentLevel = user.getRegisterLevel();
			//升级级别
			String upgradeLevel = regUserDTO.getRegisterLevel();
			//计算本次升级费用
			Long upgradeMoney = RuleDTO.level.get(upgradeLevel)-RuleDTO.level.get(currentLevel);
			
			if(balance>=upgradeMoney){
				//扣除开通费用
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(user.getLoginName());
				tr.setTransactionObject("system");
				tr.setTransactionType(TranType.HuiYuanShengJiKouChu);
				if("L6".equals(regUserDTO.getRegisterLevel()) || "L7".equals(regUserDTO.getRegisterLevel())){
					transactionRecordService.updateTran(tr, "Static", upgradeMoney.doubleValue(), CUT);
				}else{
					transactionRecordService.updateTran(tr, "Dynamic", upgradeMoney.doubleValue(), CUT);
				}

				user.setRegisterLevel(regUserDTO.getRegisterLevel());
				user.setRegisterMoney(RuleDTO.level.get(upgradeLevel));
				user.setUserUpgradeFalg("Upgrade Time:"+new Date());
				
				
				RuleDTO ruleDTO = ruleService.findRuleInfo();
				RegisterUser recommendUser=registerUserDAO.findUniqueBy("loginName",user.getRecommendUser());
				//直推奖
				System.out.println("----直推奖------");
				bonusService.directPush(user.getLoginName(), ruleDTO);
				
				//管理奖
				System.out.println("----管理奖------");
				bonusService.activeUserAward(user, recommendUser, ruleDTO);

				//代数奖/领导奖
				System.out.println("----领导奖(根据代数或推荐来拿)------");
				bonusService.algebraicAward(ruleDTO,user, recommendUser, null, 0);
				
				
				return "恭喜,升级成功!";
			}else{
				return "升级失败，余额不足!";
			}
			
		}
		
		
		/*if(user!=null && user.getActivationTime()==null){
			//判断接点人是否存在
			RegisterUser reg2 = registerUserDAO.findUniqueBy("loginName", regUserDTO.getContactNo());
			if(reg2==null)
				return "对不起，升级失败，填写的接点人不存在!";
			else if(!"Activation".equals(reg2.getStatus()) && false){
				return "对不起，升级失败，接点人未激活!";//接点人未激活，不允许注册下一层会员!
			}else{
				//判断接点人的ABC区是否已满及位置是否正确
				List<RegisterUser> abcUser = registerUserDAO.findBy("contactNo", regUserDTO.getContactNo());
				if(abcUser.size()>=2){
					return "对不起，升级失败，左右区已满!";//左右区已满
				}
				boolean au = registerUserDAO.findAreaRegUser(regUserDTO.getContactNo(), "aArea");
				boolean bu = registerUserDAO.findAreaRegUser(regUserDTO.getContactNo(), "bArea");
				if("aArea".equals(regUserDTO.getRegisterLocation())){//如果注册的是A区，则判断A区是否已注册
					if(au){
						return "对不起，升级失败，左区已注册!";//A区已注册
					}
				}
				if("bArea".equals(regUserDTO.getRegisterLocation())){//如果注册的是B区，则判断B区是否已注册
					if(bu){
						return "对不起，升级失败，右区已注册!";//B区已注册
					}else{
						if(!au){
							return "对不起，升级失败，左区未注册，右区不允许注册!";//A区未注册，B区不允许注册!
						}
					}
				}
			}
			
			
			
			//判断报单中心
			RegisterUser user1=registerUserDAO.findUniqueBy("loginName",regUserDTO.getDeclarationCenters());
			if(user==null || !user1.isDeclarationCenter()){
				return "对不起，升级失败，填写的运营中心不存在!";
			}
			//判断推荐人
			RegisterUser user2=registerUserDAO.findUniqueBy("loginName",regUserDTO.getRecommendUser());
			if(user2==null){
				return "对不起，升级失败，填写的推荐人不存在!";
			}else if(user2.getActivationTime()==null){
				return "对不起，升级失败，填写的推荐人未激活!";
			}
			//更新之前的已有的接点信息
			//updatecontact(regUserDTO.getContactNo(),regUserDTO.getRegisterLocation());
			
			user.setContactNo(regUserDTO.getContactNo());
			user.setRegisterLocation(regUserDTO.getRegisterLocation());
			user.setDeclarationCenters(regUserDTO.getDeclarationCenters());
			user.setRecommendUser(regUserDTO.getRecommendUser());
			user.setRegisterMoney(levels.get(regUserDTO.getRegisterLevel()));
			user.setRegisterLevel(regUserDTO.getRegisterLevel());
			
			
			//接点人
			if(reg2!=null)
				user.setLinkcode(reg2.getLinkcode()+regUserDTO.getLoginName());
			
			user.setUserUpgradeFalg("已使用");
			
			return "恭喜您，升级正式会员提交成功，待运营中心进行激活!";
			
		}else{
			return "对不起，升级失败，要升级的会员不存在!";
		}*/
		
	}
	
	
	private void updatecontact(String contactNo,String location){
		RegisterUser ru = registerUserDAO.findAreaRegUser1(contactNo,location);
		if(ru!=null){
			ru.setContactNo(null);
			ru.setLinkcode(null);
		}
	}
	
	private String[] findx1 (List<RegisterUser> users){
		String[] user = new String[users.size()];
		int i = 0; 
		for(RegisterUser u :users){
			user[i] = u.getLoginName();
			i++;
		}
		return user;
	}
	public String findxx(String[] recommendUsers){
//		System.out.println("---aaa1---");
		//我的接点会员
		List<RegisterUser>  users = registerUserDAO.findContactUser(recommendUsers);
		if(users.size()==0){
//			System.out.println("整层都没有");
			return recommendUsers[0]+"_aArea";
		}else if(users.size() >= recommendUsers.length*2){//整层没有空位
//			System.out.println("整层没有空位，将继续找");
			return findxx(findx1(users));
		}else if(users.size() < recommendUsers.length*2){//小于规定大小说明有空位
//			System.out.println("小于规定大小说明有空位");
			for(String str:recommendUsers){
				//如果没有A区直接返回
				List<RegisterUser>  list = registerUserDAO.findBy("contactNo", str);
				if(list.size()==0){
					return str+"_aArea";
				}else if(list.size()==1){
					/*RegisterUser ru = list.get(0);
					if(ru.getActivationTime()==null){
						System.out.println("----------2----------------");
						return str+"_aArea";
					}else{
						System.out.println("----------3----------------");
						return str+"_bArea";
					}*/
					return str+"_bArea";
				}
//				else if(list.size()==2){
//					RegisterUser ru = list.get(0);
//					if(ru.getActivationTime()==null){
//						System.out.println("----------4----------------");
//						return str+"_aArea";
//					}
//					
//					RegisterUser ru1 = list.get(1);
//					if(ru1.getActivationTime()==null){
//						System.out.println("----------5----------------");
//						return str+"_bArea";
//					}
//				}
				
			}
		}
		return null;
	}
	
	/**
	 * 根据推荐人找接点人
	 * @param recommendUser
	 * @return
	 */
	@Transactional
	public String findContactNo(String recommendUser){
		//推荐人
		RegisterUser recommend = registerUserDAO.findUniqueBy("loginName",recommendUser);
		
		if(recommend!=null){
//			System.out.println("---aaa0---");
			String result = findxx(new String[]{recommendUser});
			System.out.println("最终找到::"+result);
			return result;
		}
		return null;
	}
	
	/**
	 * 根据当前用户及注册位置找接点人
	 */
	@Transactional
	public List<RegisterUserGridDTO> findContactNo(String loginName , String registerLocation){
		List<RegisterUserGridDTO> returnList = new ArrayList<RegisterUserGridDTO>();
		List<RegisterUser> list = new ArrayList<RegisterUser>();
		RegisterUser user1 = registerUserDAO.findUniqueBy("loginName", loginName);
		String location ="aArea";
		if("aArea".equals(registerLocation)){
			//判断当前用户左区是否挂了人，如果没挂直接返回
			RegisterUser auser = registerUserDAO.findAearContactUser(loginName, "aArea");
			if(auser==null){
				list.add(user1);
			}else{
				list = registerUserDAO.findJiDianRen(auser.getLinkcode());
			}
		}else{
			//判断当前用户左区是否挂了人，如果没挂直接返回
			RegisterUser auser = registerUserDAO.findAearContactUser(loginName, "bArea");
			if(auser==null){
				list.add(user1);
				location ="bArea";
			}else{
				list = registerUserDAO.findJiDianRen(auser.getLinkcode());
			}
		}
		for(RegisterUser u : list){
			if( u != null) {
				RegisterUserGridDTO dto = new RegisterUserGridDTO();
				dto.setRegisterLocation(location);
				dto.setLoginName(u.getLoginName());
				dto.setUserName(u.getUserName());
				dto.setRegisterLevel(u.getRegisterLevel());
				returnList.add(dto);
			}
		}
		
		return returnList;
		
	}
	
	
	/**
	 * 出局判断
	 * @param loginName
	 */
	@Transactional
	public boolean userOut(String loginName){
		RegisterUser user = registerUserDAO.findUniqueBy("loginName",loginName);
		if(user!=null){
			String registerLevel=user.getRegisterLevel();
			RuleDTO ruleDTO = ruleService.findRuleInfo();
			Double stat = transactionRecordDAO.statOut(loginName);
			//我的推荐数
			Integer counts = registerUserDAO.userCount(user.getLoginName(), "AllRecActivation",new String[]{});
			Double outs = 0D;
			if(counts==0){
				outs = RuleDTO.level.get(registerLevel)*ruleDTO.getRule031();
			}else if(counts>=1 && counts<5){
				outs = RuleDTO.level.get(registerLevel)*ruleDTO.getRule032();
			}else if(counts>=5 && counts<10){
				outs = RuleDTO.level.get(registerLevel)*ruleDTO.getRule033();
			}else if(counts>=10 && counts<15){
				outs = RuleDTO.level.get(registerLevel)*ruleDTO.getRule034();
			}else if(counts>=15){
				outs = RuleDTO.level.get(registerLevel)*ruleDTO.getRule035();
			}
			if(stat>=outs){
				return true;
			}else{
				return false;
			}
		}else{
			return true;
		}
		
	}
	
	/**
	 * 
	 * @param qdto
	 * @param sord
	 * @param sidx
	 * @return
	 */
	public PageDTO findSubUserPager(RegisterUserQueryDTO qdto,String sord, String sidx){
		if ( qdto == null || !StringUtils.hasText(qdto.getParentAccount())) {
			return new PageDTO();
		}
		
		/*PageDTO p =registerUserDAO.findPager(qdto, sord, sidx);
		
		List<RegisterUser> registerUsers = (List<RegisterUser>) p.getData();
		List<RegisterUserGridDTO> userDTOList = new ArrayList<RegisterUserGridDTO>(registerUsers.size());
		for(RegisterUser regiserUser:registerUsers){
			RegisterUserGridDTO dto = new RegisterUserGridDTO();
			RegisterUserGridDTO.entity2dto(regiserUser, dto);
			dto.setAsUserName(dto.getUserName());
			dto.setUserName(dto.getUserName().substring(0, 1)+"**");
			dto.setDeclarationCenter(regiserUser.isDeclarationCenter());
			Account ac = regiserUser.getAccount();
			if(ac!=null)
				dto.setBalance(ac.getBalance());
			userDTOList.add(dto);
		}
		p.setData(userDTOList);
		*/
		return findRegisterUserPager(qdto, sord, sidx);
	}
	/**
	 * 修改用户状态
	 * @param ids
	 * @param userStatus
	 * @return
	 */
	public boolean changeUserStatus(Long[] ids,String userStatus){
		boolean result = false;
		for(Long id : ids){
			RegisterUser user  = registerUserDAO.findById(id);
			if(user!=null){
				user.setUserStatus(userStatus);
				registerUserDAO.merge(user);
				result = true;
			}
		}
		return result;
	}
	
	//用户对于账号操作统一入口
	@Transactional
	public synchronized String userOpt(String optType,
			String loginName, 
			String activeType,
			String transAccount,
			Double value,
			String dtype,
			ExtractDTO dto,
			Double moeny,
			String upLevel,Object obj){
		String result = "not opt items";
		if("userActive".equals(optType)){//会员激活
			result = userActivate(loginName, activeType);
		}else if("ZhuanZhang".equals(optType)){//转账
			result = accountService.deltaTransfer(loginName, transAccount, value, dtype);
		}else if("ChongZhi".equals(optType)){//充值
			result = userRecharge(dtype, moeny, loginName);
		}else if("TingXiangApply".equals(optType)){//提现申请
			result = extractService.apply(dto);
		}else if("UserUpgrade".equals(optType)){//会员升级 
			RegisterUserDTO regUserDTO = new RegisterUserDTO();
			regUserDTO.setRegisterLevel(upLevel);
			regUserDTO.setLoginName(loginName);
			result = userUpgrade(regUserDTO);
		}else if("TingXiangHand".equals(optType)){//提现处理
			extractService.confirm(dto);
			result = "OK";
		}else if("UserDel".equals(optType)){//删除会员
			result = this.deleteRegisterUser(loginName);
		}else if("ReTouZi".equals(optType)){//重新投资
			result = reTouZi(loginName,upLevel);
		}else if("MaiChu".equals(optType)){//卖出
			SellDTO sellDTO = (SellDTO)obj;
			result = sellService.save(sellDTO);
		}else if("MaiChuClean".equals(optType)){//卖出取消
			SellDTO sellDTO = (SellDTO)obj;
			result = sellService.clean(sellDTO);
		}else if("Buy".equals(optType)){//买入
			SellDTO sellDTO = (SellDTO)obj;
			result = sellService.buy(sellDTO);
		}else if("ConfirmPayment".equals(optType)){//卖出确认收款
			SellDTO sellDTO = (SellDTO)obj;
			result = sellService.confirmPayment(sellDTO);
		}
		
		return result;
	}
	
	
	/**
	 * 清空所有账号现金银行
	 */
	@Transactional
	public void userAccount1Clean(){
		List<RegisterUser> lists = registerUserDAO.findAll();
		for(RegisterUser user : lists){
			if(!"L6".equals(user.getLevel()) && !"subAccount".equals(user.getSubAccount())){
				System.out.println("----"+user.getLoginName());
				Double balance = transactionRecordService.findUserBalance(user.getLoginName(), "Dynamic");
				if(balance>0){
					//扣除父帐户
					TransactionRecord tr = new TransactionRecord();
					tr.setLoginName(user.getLoginName());
					tr.setTransactionObject("system");
					tr.setTransactionType(TranType.KouChu);
					transactionRecordService.updateTran(tr, "Dynamic",balance, CUT);	
				}
				
			}
		}
	}
	
	@Transactional
	public String findUserInfo(String loginName){
		RegisterUser user = registerUserDAO.findUniqueBy("loginName",loginName);
		if(user!=null && StringUtils.hasText(user.getLoginName()) && isMyTream(loginName)){
			return "<div  style='text-align: left;'>会员编号："+loginName+
					"<br>会员姓名："+user.getUserName()+
					"<br>一级密码："+user.getPassword1()+
					"<br>交易密码："+user.getPassword2()+
					"<br>密保："+user.getPasswordProblem()+
					"<br>答案："+user.getPasswordAnswer()+"</div>";
		}else{
			return "未找到会员信息!";
		}
	}
	
	
	/**
	 * 用户注册(只填写账号密)
	 */
	@Transactional
	public String regiserUser(RegisterUserDTO dto) {
		if ( dto == null 
				|| !StringUtils.hasText( dto.getLoginName() )
				|| !StringUtils.hasText( dto.getAuthCode() )
				|| !StringUtils.hasText( dto.getPassword1() )
						){
			return "ERROR_PARAM";//无效的参数
		}
		final String loginName = dto.getLoginName();
		RegisterUser reg = registerUserDAO.findUniqueBy("loginName", loginName);
		if ( reg != null ) { 
			return "LOGINNAME_ALREADY_REGISTERED";//登录名已经被注册过
		}
		boolean result = false;
		//手机验证码
		ActivationCode ac = activationCodeService.authVerificationCode(dto.getMobile(), dto.getAuthCode(), "Register");
		if (ac!=null) {
			result = true;
		}else{
			return "ACTIVATION_CODE_ERROR";
		}
		if (result) {
			reg = new RegisterUser(); RegisterUserDTO.dto2entity(dto, reg);
			reg.setDeclarationCenter( false ); reg.setRecommendQuantity(0);
			reg.setEmail(loginName); reg.setLinkcode("");
			reg.setStatus("unfinished");
			reg.setRegisterTime( new Date() );
			//Tan 默认值
			reg.setRegisterMoney(RuleDTO.level.get(dto.getRegisterLevel()));
			
			Calendar cl = new GregorianCalendar();
			cl.setTime(new Date());
			cl.set( Calendar.DATE, cl.get( Calendar.DATE )+3);
			reg.setLastOptTime(cl.getTime());
			reg.setTempTime(reg.getLastOptTime());
			registerUserDAO.save(reg);
			
			//修改验证码的状态
			if(ac!=null){
				ac.setLastUpdateTime(new Date());
				ac.setStatus(IActivationCodeService.USED);
				activationCodeDAO.merge(ac);
			}
			/*String title = "会员注册成功";
			String content ="注册成功，恭喜成为会员。请登录系统进一步完善资料！<br>如非本人操作，请直接屏蔽该邮件！谢谢！";
			
			if("EN".equals(dto.getLanguage())){
				title = "Account registration success -ZOPA";
				content = "Account registration success-ZOPA！Please login platform to improve information！<br> Non self operation, please directly shield the message! thank you！";
			}
			
			final String title1 = title;
			final String content1 = content;
			new Thread(new Runnable() {
				public void run() {
					emailService.sendMail(loginName, title1,content1);
				}
			}).start();*/
		}else{
			return "REGISTER_CODE_INVALID";//注册码无效
		}
		return "SUCCESSFUL";
	}
	
	
	/**
	 * 会员信息完善
	 */
	@Transactional
	public String updateRegisterInfo(RegisterUserDTO dto) {
		RegisterUser reg = registerUserDAO.findUniqueBy("loginName", dto.getLoginName());
		if ( reg != null) {
			if(dto.getLoginName().equals(dto.getContactNo())){
				return "successful";
			}
			if(dto.getLoginName().equals(dto.getRecommendUser())){
				return "successful";
			}
			reg.setUserName( dto.getUserName() );
			reg.setDeclarationCenters(dto.getDeclarationCenters());
			reg.setRecommendUser( dto.getRecommendUser());
			reg.setContactNo(dto.getContactNo());
			reg.setRegisterLocation(dto.getRegisterLocation());
			if ( StringUtils.hasText(dto.getPassword1()) ) {
				reg.setPassword1( dto.getPassword1() );
			}
			if ( StringUtils.hasText(dto.getPassword2()) ) {
				reg.setPassword2( dto.getPassword2() );
			}
			reg.setAccountType( dto.getAccountType() );
			reg.setBankAccount( dto.getBankAccount() );reg.setOpenBankAddress( dto.getOpenBankAddress() );
			reg.setPhone( dto.getPhone()); reg.setUserName( dto.getUserName() );
			reg.setPasswordProblem( dto.getPasswordProblem()); reg.setPasswordAnswer( dto.getPasswordAnswer());
			
			reg.setLastUpdateTime( new Date());
			reg.setStatus("NotActivation");
			reg.setRegisterLevel(dto.getRegisterLevel());
			reg.setRegisterMoney(RuleDTO.level.get(dto.getRegisterLevel()));
			
			//接点人
			RegisterUser contactUser = registerUserDAO.findUniqueBy("loginName", dto.getContactNo());
			if(contactUser!=null){
				reg.setLinkcode(contactUser.getLinkcode()+dto.getLoginName());
				//层级累计
				reg.setLevel(contactUser.getLevel()+1);
			}

			//推荐数统计
			/*RegisterUser recommendUser = registerUserDAO.findUniqueBy("loginName",reg.getRecommendUser());
			if(recommendUser!=null){
				recommendUser.setRecommendQuantity(recommendUser.getRecommendQuantity()+1);
			}*/
			//总利益
			registerUserDAO.update(reg);
			dto.setStatus(reg.getStatus());
			sessionInit(reg);//修改信息之后，初始化一下session
			return "successful";
		}
		return null;
	}
	
	@Transactional
	public String changeMobile(RegUserBasicDTO rbDto) {
		// TODO Auto-generated method stub
		RegisterUser reg = registerUserDAO.findUniqueBy("loginName", rbDto.getLoginName());
		if(reg==null){
			return "会员账号不存在，请检查!";
		}
		//原手机验证码
		ActivationCode ac = activationCodeService.authVerificationCode(rbDto.getMobile(), rbDto.getOldAuthCode(), "ChangeMobile");
		if (ac != null) {//为true时验证通过
			ac.setStatus("已使用");
			ac.setLastUpdateTime(new Date());
			activationCodeDAO.merge(ac);
		}else{
			return "原手机验证码不正确!";
		}
		//新手机验证码
		ActivationCode ac1 = activationCodeService.authVerificationCode(rbDto.getNewMobile(), rbDto.getAuthCode(), "ChangeMobile");
		if (ac1 != null) {//为true时验证通过
			ac1.setStatus("已使用");
			ac1.setLastUpdateTime(new Date());
			activationCodeDAO.merge(ac1);
		}else{
			return "新手机验证码不正确!";
		}
		reg.setMobile(rbDto.getNewMobile());
		return "手机号码修改成功!";
	}
	
	
	public void batchAddUser(int rows){
		for(int i=0;i<=rows;i++){
			String loginName = (i+1)+"";
			RegisterUser entity = new RegisterUser();
			entity.setLoginName(loginName);
			entity.setPassword1(loginName);
			entity.setPassword2(loginName);
			entity.setUserName(loginName);
			entity.setRegisterLevel("L5");
			entity.setRegisterMoney(20000L);
			entity.setActivationTime(new Date());
			entity.setRegisterTime(new Date());
			entity.setStatus("Activation");
			entity.setEmail("system@ds.com");
			entity.setDeclarationCenter(true);
			entity.setRecommendQuantity(0);
			entity.setLinkcode("0000");
			entity.setLevel(5L);
			registerUserDAO.save(entity);
			
			
			//70%回购
			TransactionRecord tr2 = new TransactionRecord();
			tr2.setLoginName(entity.getLoginName());
			tr2.setTransactionObject("System");
			tr2.setTransactionType(TranType.ChongZhi);
			tr2.setRemark("会员激活回购70%");
			transactionRecordService.updateTran(tr2, TranType.STATIC, RuleDTO.level.get(entity.getRegisterLevel())*0.7, ADD);
			
			
			//自动挂出
			BuyDTO buyDto = new BuyDTO();
			buyDto.setBuyUser(loginName);
			buyService.save(buyDto);
			
		}
	}
	/**
	 * 重新投资
	 * @param loginName
	 * @param reLevel
	 * @return
	 */
	@Transactional
	public String reTouZi(String loginName,String reLevel){
		//得到当前用户
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName",loginName);
		//检查余额是否足够
		Double balance = 0D; 
		balance = transactionRecordService.findUserBalance(loginName, TranType.DYNAMIC);
		
		String registerLevel = reLevel;
		if(regUser!=null &&  "Activation".equals(regUser.getStatus()) && regUser.getIssued()==0 &&  balance>=RuleDTO.level.get(registerLevel)){
			//扣除开通费用
			TransactionRecord tr = new TransactionRecord();
			tr.setLoginName(loginName);
			tr.setTransactionObject("system");
			tr.setTransactionType(TranType.HuiYuanKaiTongKouChu);
			transactionRecordService.updateTran(tr, TranType.DYNAMIC, RuleDTO.level.get(registerLevel).doubleValue(), CUT);
			
			Long reTouZiMoney = RuleDTO.level.get(registerLevel);
			regUser.setRegisterLevel(registerLevel);
			regUser.setRegisterMoney(reTouZiMoney);
			//注册账户(80%)
			regUser.setTotalIncome(reTouZiMoney+reTouZiMoney*80/100);
			regUser.setIssued(reTouZiMoney+reTouZiMoney*80/100);
		
			TransactionRecord tr_rega = new TransactionRecord();
			tr_rega.setLoginName(regUser.getLoginName());
			tr_rega.setTransactionObject("System");
			tr_rega.setTransactionType(TranType.TouZiShouYi);
			transactionRecordService.updateTran(tr_rega, TranType.STATIC, reTouZiMoney+reTouZiMoney*0.8, TranType.ADD);
			
			
			RuleDTO ruleDTO = ruleService.findRuleInfo();
			//用户有效期
			Calendar ct = new GregorianCalendar(  );
			ct.setTime( new Date());
			ct.set(Calendar.DATE,ct.get(Calendar.DATE)+ruleDTO.getYifenghong2().intValue());
			regUser.setValidTime(ct.getTime());
			
			RegisterUser recommendUser = registerUserDAO.findUniqueBy("loginName",regUser.getRecommendUser());
			
			//直推奖
			System.out.println("----复投-直推奖------");
			bonusService.directPush(loginName, ruleDTO);
			
			//管理奖
			System.out.println("----复投-管理奖------");
			bonusService.activeUserAward(regUser, recommendUser, ruleDTO);

			//代数奖/领导奖
			System.out.println("----复投-领导奖(根据代数或推荐来拿)------");
			bonusService.algebraicAward(ruleDTO,regUser, recommendUser,null, 0);
			
		}else{
			return "复投失败,请检查是否有足够的余额!";
		}
		return "恭喜，复投成功!";
	}
}
